无法填写列表

时间:2017-02-08 12:00:43

标签: c# .net linq

我正在下课:

 public class statistics
    {
        public int Type { get; set; }
        public string Title { get; set; }
        public bool Flag { get; set; }
    }

以上是统计类的列表,因此它包含如下记录:

1st record : Type = 1
             Title = "abc,ttt"
             flag= true

2nd Records : Type = 1
             Title = "xyz"
             flag= true

3rd Records : Type = 1
              Title = "lmn,ggg"
              flag= true

所以在这里我想操纵我的统计变量,所以我的 统计变量应包含 5条记录,如下所示:

1st record : Type = 1
             Title = "abc"
             flag= true


2nd record : Type = 1
             Title = "ttt"
             flag= true

3rd Records : Type = 
             Title = "xyz"
             flag= true

4th Records : Type = 1
              Title = "lmn"
              flag= true

5th Records : Type = 1
              Title = "ggg"
              flag= true

因为你可以看到,如果title包含以逗号分隔的记录,我想要一个单独的记录。

For eg:1st record : Type = 1
             Title = "abc,ttt"
             flag= true

abc和ttt应分成两个记录,因为标题包含以逗号分隔的记录。

这是我尝试但无法做到的方式:

statistics = statistics.Select(o => o.Title.Split(',')).
                            Select(
                                        t => new statistics
                                        {
                                            Type = t.   // not working
                                        }
                                        ).ToList();

4 个答案:

答案 0 :(得分:3)

您似乎正在寻找Split(将单个逗号分隔 Type转换为多个项目)和SelectMany(以展平集合):

List<statistics> source = .....;

var result = source
  .SelectMany(item => item.Title //split title 
     .Split(',')
     .Select(title => new statistics() {
        Type = item.Type,
        Title = title,
        Flag = item.Flag }))
  .ToList(); // finally, materialize into list

答案 1 :(得分:1)

你需要这样的东西:

var result = statistics.Select(s => s.Title.Split(',')
    .Select(x => new statistics {Type = s.Type, Flag = s.Flag, Title = x}))
    .SelectMany(s=>s)
    .ToList();

使用此输出:

enter image description here

答案 2 :(得分:1)

var result = statistics.SelectMany(s => s.Title.Split(new char[] { ',' }).
Select(t => new statistics() { Title = t, Flag = s.Flag, Type = s.Type }));

答案 3 :(得分:1)

查询语法稍微好一点,但不要对类和列表使用相同的名称statistics

var result = (from s in statistics
              from a in s.Title.Split(',')
              select new statistics(){ Type = s.Type, Title = a, Flag = s.Flag }).ToList();