LINQ:按索引和值分组 [英] LINQ: Group by index and value
本文介绍了LINQ:按索引和值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个包含以下值的字符串列表:
Lets say I have an list of strings with the following values:
["a","a","b","a","a","a","c","c"]
["a","a","b","a","a","a","c","c"]
我想执行一个linq查询,该查询将分为4组:
I want to execute a linq query that will group into 4 groups:
第1组:["a","a"]第2组:["b"]第3组:["a","a","a"]第4组: ["c","c"]
Group 1: ["a","a"] Group 2: ["b"] Group 3: ["a","a","a"] Group 4: ["c","c"]
基本上,我想为值"a"创建2个不同的组,因为它们不是来自同一索引序列".
Basically I want to create 2 different groups for the value "a" because they are not coming from the same "index sequence".
有人为此提供LINQ解决方案吗?
Anyone has a LINQ solution for this?
推荐答案
您只需要键而不是数组项
You just need key other than items of array
var x = new string[] { "a", "a", "a", "b", "a", "a", "c" };
int groupId = -1;
var result = x.Select((s, i) => new
{
value = s,
groupId = (i > 0 && x[i - 1] == s) ? groupId : ++groupId
}).GroupBy(u => new { groupId });
foreach (var item in result)
{
Console.WriteLine(item.Key);
foreach (var inner in item)
{
Console.WriteLine(" => " + inner.value);
}
}
结果如下:链接
这篇关于LINQ:按索引和值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文