Linq:使用非唯一键分组(保留顺序)

时间:2017-12-28 01:13:21

标签: linq

假设列表类似于a-a-a-b-b-a-c-c-c-a-a,我该如何获取组 {A-A-A} - {B-B} - {A} - {C-C-C} - {的a-a}

所以不是我想要的是:{a-a-a-a-a-a} - {b-b} - {c-c-c}。

2 个答案:

答案 0 :(得分:1)

尝试以下代码;

var list = new List<string>
{
    "a","a","a","b","b","a","c","c","c","a","a"
};
int index = 0;
string lastItem = "";
var groupedList = 
    list
    .Select(x =>
    {
        if (lastItem != x)
        {
            index++;
            lastItem = x;
        }
        return new { Item = x,Index = index };
    })
    .GroupBy(grp => grp)
    .Select(grp => grp.Select(x => x.Item).ToList())
    .ToList();

<强>输出

a,a,a
b,b
a
c,c,c
a,a

答案 1 :(得分:1)

    public static List<(string key, List<T> items)> GroupByConsecutive<T>( 
          IEnumerable<T> items,   
          Func<T, string> key)
    {
        var list = new List<(string key, List<T> items)>();

        foreach (var item in items)
        {
            if (list.Count == 0 || list.Last().key != key(item))
            {
                list.Add((key(item), new List<T> { item }));
            }
            else
            {
                list.Last().items.Add(item);
            }
        }

        return list;
    }