我正在读取一个csv文件,我想将第二列添加到与名称匹配的列相同的列表中。我检查下一行是否等于上一条记录,但是然后循环查找匹配的数组,但不确定如何将internalList重新添加到类对象中。
有更好的方法吗?
程序
while ((s = sr.ReadLine()) != null)
{
string[] words = s.Split('\t');
if (previousrecord == words[0])
{
for (int i = 0; i < ALEComName.Count; ++i)
{
}
}
else
{
Name person = new Name();
person.Name = words[0];
List<SubName> internalList = new List<SubName>();
SubName AssociatedSub = new SubName { Name = words[1] };
internalList.Add(AssociatedSub);
person.AssociatedSub = internalList;
ALEComName.Add(Disease);
}
previousrecord = words[0];
Dto
public class Name
{
public string Name { get; set; }
public List<SubName> AssociatedSub { get; set; }
}
public class SubName
{
public string Name { get; set; }
}
}
CSV文件
A A
B B
C A
C B
C C
D A
D B
答案 0 :(得分:1)
您可以阅读所有行,然后使用Linq:
var data = File.ReadAllLines(@"c:\temp\sample.txt");
var names = data.Select(d => d.Split('\t'))
.Select(s => new { Name = s[0], SubName = s[1] })
.GroupBy(o => o.Name)
.Select(g => new Name()
{
Name1 = g.Key,
AssociatedSub = g.Select(v => new SubName() { Name = v.SubName }).ToList()
});
//This part is just to show the output
foreach (var name in names)
{
Console.WriteLine($"Name: {name.Name1}, AssociatedSub: {string.Join(",", name.AssociatedSub.Select(s => s.Name).ToArray())}");
}
输出:
名称:A,关联子:A
名称:B,关联子:B
名称:C,关联子:A,B,C
名称:D,关联子:A,B
由于属性结构无效,我不得不将属性名称更改为Name1
。
您首先选择拆分的结果,然后使用Name
和SubName
属性创建用于分组的匿名类型。最后,您从分组结果中选择并创建实例。
这只是一个快速示例,因此请小心避免Split
之类的错误,未返回预期的零件数。
答案 1 :(得分:0)
Linq方法非常好,我同意这个想法。如果您想要一种更保守的方式,该方法可以存储键,值对。
class Program {
static void Main(string[] args) {
using(var file = new StreamReader(@"../file.csv")) {
var dict = new Dictionary<string, List<string>>();
List<string> split;
string line, key;
while((line = file.ReadLine()) != null) {
split = line.Select(l => new string(l, 1)).Where(l => l != " ").ToList();
key = split[0];
split.RemoveAt(0);
if(dict.ContainsKey(key)) {
dict.TryGetValue(key, out var values);
values.AddRange(split);
} else dict.Add(key, split);
}
foreach(KeyValuePair<string, List<string>> r in dict) {
foreach(var val in r.Value) {
Console.WriteLine("Main = {0}, Sub = {1}", r.Key, val);
}
}
}
}
}