在c#中合并数组中的重复项

时间:2015-05-08 07:24:52

标签: c# arrays

所以我有2个像这样的阵列:

array1 = {1,2,3,4};
array2 = {353, 588, 213, 353};

array1中的数字对应于array2中的相应索引,因此它意味着:353中的1个,588中的2个,213个中的3个,353个中的4个。我希望能够合并数组2中的重复项最后一个成为:

array1 = {5,2,3};
array2 = {353,588,213};

我在考虑循环,但我认为它效率低下,所以我希望有人知道最有效的方法。

提前致谢!

这是另一个例子

array1 = {14,2,3,8,10,2,7,9};
array2 = {353, 588, 353, 213, 588, 213, 200, 353};

array1 = {26,12,10,7};
array2 = {353,588,213,200};

4 个答案:

答案 0 :(得分:8)

你可以使用一个词典,其中键是array2的值,字典的值是计数:

$sql = "SELECT * FROM $table WHERE id = '$userId'";

$result = mysql_query($sql) or Die('Query failed: ' . mysql_error()); 
echo 'Registration Complete'; 

然后,要再次将字典转换为数组,您只需要迭代它:

var dic = new Dictionary<int, int>();
for(int i = 0; i < array2.Length; i++) {
    int index = array2[i];
    if(dic.ContainsKey(index)) {
        dic[index] += array1[i];
    } else {
        dic.Add(index, array1[i]);
    }
}

Demo

答案 1 :(得分:4)

demo

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var array1 = new int[]{1,2,3,4};
        var array2 = new int[]{353, 588, 213, 353};

        var result = array1.Zip(array2, (a1, a2)=>new {Index = a1, Value = a2})
                           .GroupBy(pair=>pair.Value).ToList();

        array2 = result.Select(gr=>gr.Key).ToArray();
        array1 = result.Select(gr=>gr.Sum(pair=>pair.Index)).ToArray();

        Console.WriteLine(String.Join(", ", array1));       
        Console.WriteLine(String.Join(", ", array2));
    }
}

答案 2 :(得分:2)

您可以使用LINQ获取合并数据。使用Enumerable.Zip方法很容易,它从两个序列中的相应元素(在您的情况下为array1和array2)中生成结果序列。它会产生一对elemens:

{ a1 = 1, a2 = 353 }
{ a1 = 2, a2 = 213 }
{ a1 = 3, a2 = 588 }
{ a1 = 4, a2 = 353 }

下一步是用{2}分组Enumerable.GroupBy。它会产生一组对

{ Key = 353, [{ a1 = 1, a2 = 353 }, { a1 = 4, a2 = 353 }] }
{ Key = 213, [{ a1 = 2, a2 = 213 }] }
{ Key = 588, [{ a1 = 3, a2 = 588 }] }

然后只需从每个组中选择所需内容并将结果放入适当的数组:

var groups = array1.Zip(array2, (a1,a2) => new { a1, a2 })
                   .GroupBy(x => x.a2)
                   .ToArray();

array1 = groups.Select(g => g.Sum(x => x.a1)).ToArray();
array2 = groups.Select(g => g.Key).ToArray();

答案 3 :(得分:1)

int[] array1 = new int[] { 14, 2, 3, 8, 10, 2, 7, 9 };
int[] array2 = new int[] { 353, 588, 353, 213, 588, 213, 200, 353 };

// merge
Dictionary<int, int> dic = new Dictionary<int, int>();
int count = array1.Length;
int sum;
for (int i = 0; i < count; i++)
{
    int a = array1[i];
    int b = array2[i];
    dic[b] = a + (dic.TryGetValue(b, out sum) ? sum : 0);
}

int[] convertedArray1 = dic.Values.ToArray();
int[] convertedArray2 = dic.Keys.ToArray();

// result is:
// convertedArray1 = { 26, 12, 10, 7 }
// convertedArray2 = { 353, 588, 213, 200 }