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
740 views
in Technique[技术] by (71.8m points)

wpf - How to group consecutive similar items of a collection?

Consider the following collection.

  • True
  • False
  • False
  • False
  • True
  • True
  • False
  • False

I want to display it in a structured way, say, in a TreeView. I want to be able to draw borders around entire groups and such.

  • True Group
    • True
  • False Group
    • False
    • False
    • False
  • True Group
    • True
    • True
  • False Group
    • False
    • False

How do I accomplish this with as little procedural code as possible?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This does what you're looking for and is generic:

private static IEnumerable<IGrouping<int, T>> GroupConsecutive<T>(this IEnumerable<T> set, Func<T, T, bool> predicate)
{
    var i = 0;
    var k = 0;
    var ranges = from e in set
                 let idx = ++i
                 let next = set.ElementAtOrDefault(idx)
                 let key = (predicate(e, next)) ? k : k++
                 group e by key into g
                 select g;
    return ranges;
}

Usage:

var set = new List<bool>
            {
                true,
                false,
                false,
                false,
                true,
                true,
                false,
                false,
            };
var groups = set.GroupConsecutive((b1, b2) => (b1 == b2));
foreach (var g in groups)
{
    Console.WriteLine(g.Key);
    foreach (var b in g)
        Console.WriteLine("{0}", b);
}

Output:

0
        True
1
        False
        False
        False
2
        True
        True
3
        False
        False

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

...