如何总结重复元件的值在阵列
问题描述:
我有两个阵列:如何总结重复元件的值在阵列
string[] fruit = { "apple", "banana", "lemon", "apple", "lemon" };
int[] quantity = { 2, 4, 1, 2, 2 };
第二个具有第一个相同长度,而整数各自果的量。
我想创建这两个数组:
totalefruit = { "apple", "banana", "lemon" };
totalquantity = {4, 4, 3}
答
试试这个:
string[] fruit = { "apple", "banana", "lemon", "apple", "lemon" };
int[] quantity = { 2, 4, 1, 2, 2 };
var result =
fruit
.Zip(quantity, (f, q) => new { f, q })
.GroupBy(x => x.f, x => x.q)
.Select(x => new { Fruit = x.Key, Quantity = x.Sum() })
.ToArray();
var totalefruit = result.Select(x => x.Fruit).ToArray();
var totalquantity = result.Select(x => x.Quantity).ToArray();
result
看起来是这样的:
+0
是的!这就是我需要的。谢谢 –
答
你可以使用Zip
和查找:
var fruitQuantityLookup = fruit
.Zip(quantity, (f, q) => new { Fruit = f, Quantity = q })
.ToLookup(x => x.Fruit, x => x.Quantity);
string[] totalefruit = fruitQuantityLookup.Select(fq => fq.Key).ToArray();
int[] totalquantity = fruitQuantityLookup.Select(fq => fq.Sum()).ToArray();
+0
它的工作原理!谢谢 –
具体问题是什么? –
你有试过什么吗?谨慎展示? – rbm
为什么你会有2个数组来存储这些值?你应该看看'词典' –
RandomStranger