C# 如何对数组中重复元素的值求和
我有两个阵列:C# 如何对数组中重复元素的值求和,c#,C#,我有两个阵列: string[] fruit = { "apple", "banana", "lemon", "apple", "lemon" }; int[] quantity = { 2, 4, 1, 2, 2 }; 第二个与第一个长度相同,整数表示每个水果的数量 我想创建以下两个阵列: totalefruit = { "apple", "banana", "lemon" }; totalquantity = {4,
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();
结果
如下所示:
您可以使用
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();
具体问题是什么?你试过什么吗?是否要显示?为什么要使用2个数组来存储这些值?你应该看看
字典
你应该看看如何创建一个对象,甚至是一个我不知道字典的二维数组。我来看看。谢谢!这就是我需要的。非常感谢。