首页 > 解决方案 > Merge, Union, Intersect C# List of Objects

问题描述

I am trying to solve this problem:

I have multiple array of string with some having duplicate items. I need to come up with a final list that has most items in each list

a1 = Array{"A", "B", "C","D","E","F"}; 
a2 = Array{"A", "B", "B", "C","D","D","D","E","F"}; 
a3 = Array{"A", "B", "B", "C","D","D","E","F"};
a4 =  Array{"A", "B", "B", "B", "C","D","D","E","F"}; 
a5 = Array{"A", "B", "B", ","D","D","E","E","F"};

Final result should be:

FinalArray = {"A", "B", "B", "B", "C","D","D","D","E","E""F"};

Max. occurrence each items accounted in the final result.

How can I achieve this?

标签: c#listlinqc#-4.0ienumerable

解决方案


简单的。

var arrays = new[]
{
    new[] {"A", "B", "C", "D", "E", "F"},
    new[] {"A", "B", "B", "C", "D", "D", "D", "E", "F"},
    new[] {"A", "B", "B", "C", "D", "D", "E", "F"},
    new[] {"A", "B", "B", "B", "C", "D", "D", "E", "F"},
    new[] {"A", "B", "B", "C", "D", "E", "E", "F"},
};

var result =
    arrays
        .SelectMany(xs => xs.GroupBy(x => x).Select(x => new { x.Key, Count = x.Count() }))
        .GroupBy(x => x.Key, x => x.Count)
        .Select(x => new { x.Key, Count = x.Max() })
        .SelectMany(x => Enumerable.Repeat(x.Key, x.Count))
        .ToArray();

这给出了:A, B, B, B, C, D, D, D, E, E, F


推荐阅读