我正在将字符串从文本文件读取到string[]中。文本文件有顺序的数据,例如,第一个7元素被认为是一个记录,下一个7元素被认为是第二个记录,等等。
我需要将这些记录存储在对象中,所以最后我将有一个对象列表(List<Settlement>)。
我一直在寻找建议使用LINQ的解决方案,但我没有它的背景。
下面是一个示例文件
public static List<Settlement> ReadFromLogFile()
{
string filename = path + @"\BM_DB_MIGRATION.txt";
List<Settlement> settlements = new List<Settlement>();
if (File.Exists(filename))
{
string[] lines = File.ReadAllLines(filename);
// Reading 7 elements from lines into an object of Settelment at each iteration
// and store the object in a list of objects...
}
return settlements;
}发布于 2019-09-12 08:22:02
看起来,您正在寻找GroupBy (Linq):
line #0 - group #0
line #1 - group #0
...
line #6 - group #0
line #7 - group #1
...
line #13 - group #1
line #14 - group #2
...代码:
using System.IO;
using System.Linq;
...
public static List<Settlement> ReadFromLogFile() {
string filename = Path.Combine(path, @"BM_DB_MIGRATION.txt");
if (File.Exists(filename)) {
return File
.ReadLines(filename)
.Select((line, index) => new {
line,
index
})
.GroupBy(item => item.index / 7, // group of [0..6] lines, then [7..13] lines etc.
item => item.line)
.Select(group => group.ToArray()) // Let's optimize group items access
.Select(group => new Settlement( // turn 7 lines into Settlement
//TODO: put the right Settlement constructor's syntax here
group.ElementAtOrDefault(0), // ...OrDefault - null, if line doesn't exist
group.ElementAtOrDefault(1),
group.ElementAtOrDefault(2),
group.ElementAtOrDefault(3),
group.ElementAtOrDefault(4),
group.ElementAtOrDefault(5),
group.ElementAtOrDefault(6)
))
.ToList();
}
return new List<Settlement>();
}发布于 2019-09-12 08:25:47
一个没有LINQ的例子:
public static List<Settlement> ReadFromLogFile()
{
string filename = path + @"\BM_DB_MIGRATION.txt";
List<Settlement> settlements = new List<Settlement>();
if (File.Exists(filename))
{
string[] lines = File.ReadAllLines(filename);
// Reading 7 elements from lines into an object of Settelment at each iteration
// and store the object in a list of objects...
var record = new List<string>(7);
foreach (var line in lines)
{
if (record.Count == 7)
{
// convert the lines to the Settlement data structure
var s = new Settlement(record);
settlements.Add(s);
record.Clear();
}
record.Add(line);
}
}
return settlements;
}发布于 2019-09-12 08:35:13
假设您的解决方案类的构造函数接受一个字符串数组,这将使用跳过和拿走 LINQ方法一次读取7行,同时迭代您从文件中读取的行:
public static List<Settlement> ReadFromLogFile()
{
string filename = path + @"\BM_DB_MIGRATION.txt";
List<Settlement> settlements = new List<Settlement>();
if (File.Exists(filename))
{
string[] lines = File.ReadAllLines(filename);
// Reading 7 elements from lines into an object of Settelment at each iteration
// and store the object in a list of objects...
for(int i = 0; i < lines.length; i += 7)
{
var obj = lines.Skip(i).Take(7).ToArray();
var settlement = new Settlement(obj);
settlements.Add(settlement);
}
}
return settlements;
}https://stackoverflow.com/questions/57902447
复制相似问题