0

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

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 to Objects 实现这样的结果?我看到使用 for 循环来实现这一点是多么容易,但我想知道是否有更清洁的方法可以使用 Linq 来做到这一点,但我似乎找不到任何方法。

4

1 回答 1

0

这在以下条件下可以解决问题:

1) 可以识别标题线,它以常量值开头(如果需要,可以更改此条件)

2) 对于每个“随机文本”行,可以找到相应的持续时间行。

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();
于 2012-08-07T13:39:42.620 回答