【问题标题】:C# object to list c#C# 对象列表 c#
【发布时间】:2019-04-13 10:10:14
【问题描述】:

我正在读取一个 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

【问题讨论】:

    标签: c# arraylist listobject


    【解决方案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,因为它是无效的语言结构。

    您首先选择拆分的结果,然后创建一个具有NameSubName 属性的匿名类型,用于分组。最后,从分组结果中进行选择并创建实例。

    这只是一个快速示例,因此请注意Split 未返回预期的零件数量等错误。

    【讨论】:

      【解决方案2】:

      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);
                          }
                      }
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2016-01-10
        • 1970-01-01
        • 1970-01-01
        • 2019-02-11
        • 2019-04-26
        • 2015-07-13
        • 2017-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多