分组导致匿名类型

时间:2012-08-07 07:51:58

标签: linq linq-group

我有一个字符串列表,例如这个

heading1 00:01:20
randomText
01:23
randomText2
01:45
randomText3
02:10
heading2 00:05:20
randomText4
07:25
randomText5
04:35
randomText6
09:12
etc.

我想要做的是使用Linq获取匿名类型列表,例如

{ Name = "randomText1", Category = "Heading1", Duration = "01:23"}
{ Name = "randomText2", Category = "Heading1", Duration = "01:45"}
...
{ Name = "randomText6", Category = "Heading2", Duration = "09:12"}

有什么方法可以用Linq到对象来实现这样的结果吗?我看到使用for循环如何轻松实现这一点,但我想知道是否有更简洁的方法来使用Linq,我似乎无法找到任何。

1 个答案:

答案 0 :(得分:0)

这可以满足以下条件:

1)可以识别标题行,它以常数值开始    (如果需要,可以改变这种情况)

2)对于每个“randomtext”行,都可以找到相应的持续时间行。

var data = new List<string>() {
    "heading1 00:01:20",
    "randomText       ",
    "01:23            ",
    "randomText2      ",
    "01:45            ",
    "randomText3      ",
    "02:10            ",
    "heading2 00:05:20",
    "randomText4      ",
    "07:25            ",
    "randomText5      ",
    "04:35            ",
    "randomText6      ",
    "09:12            "
};

const string HEADINGSTART = "heading";                      // TODO: Set correct value
var temp = Enumerable.Range(0, data.Count - 1)              // Iterate based on index
    .Where(i => data[i].StartsWith(HEADINGSTART))           // Find the headings
    .Select(i => new {                                      // Project to heading + data
        Heading = data[i],
        Data = data.Skip(i + 1).TakeWhile(d => !d.StartsWith(HEADINGSTART)).ToList()
    })
    .SelectMany(d => d.Data.Select(d2 => new {              // Project to single enumerable
        Heading = d.Heading,
        Data = d2
    }))
    .ToList();
var result = Enumerable.Range(0, temp.Count / 2)            // Again, iterate based on index
    .Select(i => new {                                      // Project to requested object
        Name = temp[i * 2].Data,
        Category = temp[i * 2].Heading,
        Duration = temp[i * 2 + 1].Data
    })
    .ToList();