Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何对数组中重复元素的值求和_C# - Fatal编程技术网

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个数组来存储这些值?你应该看看
字典
你应该看看如何创建一个对象,甚至是一个我不知道字典的二维数组。我来看看。谢谢!这就是我需要的。非常感谢。