Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

c# - how to count conditioned continuous values in a list with linq?

I've list like this:

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

So, Can I find how much indexes have "0" value continuously and which are their indexes - even if interrupts by "1" (not 2) - ? For example;

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..

So, the answer is 270 (before 1) + 190 (after 1) = 460 Although between 1080 and 1299 indexes have 0, they should not be considered because previous values are "2".

How can I find their sum and indexes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

LINQ version as requested:

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

Result:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...