How to find consecutive same values items as a Linq group

前端 未结 4 1108
無奈伤痛
無奈伤痛 2021-01-29 09:23
var schedules = new List{
    new Item { Id=1, Name = \"S\" },
    new Item { Id=2, Name = \"P\" },
    new Item { Id=3, Name = \"X\" },
    new Item { Id=4,         


        
4条回答
  •  粉色の甜心
    2021-01-29 09:56

    You can do it by maintaining the count of items that you found so far. This helps you find consecutive items, because the value of count(name) - index is invariant for them:

    IDictionary count = new Dictionary();
    var groups = schedules
        .Select((s, i) => new {
            Item = s
        ,   Index = i
        })
        .GroupBy(p => {
            var name = p.Item.Name;
            int current;
            if (!count.TryGetValue(name, out current)) {
                current = 0;
                count.Add(name, current);
            }
            count[name] = current + 1;
            return new { Name = name, Order = current - p.Index };
        })
        .Select(g => g.ToList())
        .Where(g => g.Count > 1)
        .ToList();
    

    This produces the desired output for your example:

    { Item = Id=3 Name=X, Index = 2 }
    { Item = Id=4 Name=X, Index = 3 }
    -----
    { Item = Id=5 Name=P, Index = 4 }
    { Item = Id=6 Name=P, Index = 5 }
    { Item = Id=7 Name=P, Index = 6 }
    

    Demo.

    Note: If Order = current - p.Index expression looks a little like "magic", consider removing the final Select and Where clauses, and enumerating group keys.

提交回复
热议问题