ZerosAndOnes
ZerosAndOnes

Reputation: 1093

LINQ Union with duplicates

Let's say we have the following three lists:

{ 1, 2, 2, 3 }
{ 2, 3, 3, 4 }
{ 2, 3, 4, 5, 5, 5 }

How can we then convert the above to a list having each item repeated the maximum number of times it's found in a list.i.e.,

{1, 2, 2 (Found twice in list 1), 3, 3 (Twice in list 2), 4, 5, 5, 5 (Thrice in list 3)}

I can achieve the above through loops, however, I am looking for a LINQ method that might already be there.

The question is similar to list union with duplicates in python

Upvotes: 2

Views: 858

Answers (2)

Enigmativity
Enigmativity

Reputation: 117064

Here you go:

var xs = new [] { 1, 2, 2, 3 };
var ys = new [] { 2, 3, 3, 4 };
var zs = new [] { 2, 3, 4, 5, 5, 5 };

var result =
    xs
        .ToLookup(x => x)
        .Concat(ys.ToLookup(x => x))
        .Concat(zs.ToLookup(x => x))
        .GroupBy(x => x.Key)
        .Select(x => new { x.Key, count = x.Max(y => y.Count()) })
        .SelectMany(x => Enumerable.Repeat(x.Key, x.count));

It gives the result you want.

Upvotes: 2

fubo
fubo

Reputation: 45947

Linq in one line

int[][] items = { new[]{ 1, 2, 2, 3 }, new[] { 2, 3, 3, 4 }, new[] { 2, 3, 4, 5, 5, 5 } };
var result = items.SelectMany(x => x.GroupBy(y => y)).GroupBy(x => x.Key).Select(x => x.OrderByDescending(y => y.Count()).First()).SelectMany(x => x);

https://dotnetfiddle.net/kZhseg

Upvotes: 6

Related Questions