如何对数组中重复元素的值求和

时间:2016-11-15 12:55:58

标签: c#

我有两个数组:

string[] fruit = { "apple", "banana", "lemon", "apple", "lemon" };
int[] quantity = { 2,          4,        1,      2,       2 };

第二个长度与第一个长度相同,整数是每个水果的数量。

我想创建这两个数组:

totalefruit = { "apple", "banana", "lemon" };
totalquantity = {4,          4,       3}

2 个答案:

答案 0 :(得分:2)

试试这个:

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看起来像这样:

result

答案 1 :(得分:2)

您可以使用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();