如何使用linq计算列表中的条件连续值?

时间:2014-03-12 08:27:44

标签: c# linq list indexing

我的列表如下:

var query = Enumerable.Range(0, 1440).Select((n, index) =>
{
    if ((index >= 480 && index <= 749) || (index >= 810 && index <= 999) || (index >= 1080 && index <= 1299))
        return 0;
    else if (index >= 750 && index <= 809)
        return 1;
    else
        return 2;
});

那么,我能找到多少索引连续有“0”值,哪些是它们的索引 - 即使中断为“1”(不是2) - ?例如;

query[480]=query[481]=query[482]....query[749] = 0, 
query[750]=query[751]...query[809] = 1, 
query[810]=query[811]....query[999] = 0, 
query[1000]?query[1001]...query[1079] = 2, 
query[1080]=query[1081]....query[1299] = 0, etc..

所以,答案是270(在1之前)+ 190(在1之后)= 460 虽然1080和1299之间的索引为0,但不应考虑它们,因为之前的值为“2”。

如何找到它们的总和和索引?

1 个答案:

答案 0 :(得分:2)

按要求提供LINQ版本:

int groupCount = 0;
var result = query
    .Select((x, i) => new { Value = x, Index = i })
    .SkipWhile(x => x.Value != 0)                   // Skip until first 0 is reached
    .TakeWhile(x => x.Value == 0 || x.Value == 1)   // Take a continuous series of 0 and 1
    .Where(x => x.Value == 0)                       // Filter out the 1s
    .GroupBy(x =>
        // Treat as a new group if it's:
        // 1) the 1st element, or
        // 2) doesn't equal to previous number
        x.Index == 0 || x.Value != query.ElementAt(x.Index - 1)
            ? ++groupCount
            : groupCount)
    .Select(x => new
    {
        Count = x.Count(),
        Start = x.First().Index,
        End = x.Last().Index
    });

结果:

{ Count = 270, Start = 480, End = 749 }
{ Count = 190, Start = 810, End = 999 }