Ian Ian - 1 month ago 6
C# Question

C# different values into one group

if I have

var numbers = new List<string> { "1", "2", "2", "3", "3"};


and I wanna to get the values (below) from numbers (above)

[["1","2","3"],["2","3"]]


every array has the different value, so I will get 2 array

more example :
new List { "1", "2", "3", "3",} to [["1","2","3"],["3"]]

rules:
different values in one array or list

Can anyone suggest how to do that easily? Thanks!

Answer

This works for me:

var numbers = new List<string> { "1", "2", "2", "3", "3"};

var lookup = numbers.ToLookup(n => n);

var results =
    Enumerable
        .Range(0, numbers.Count())
        .Select(n =>
            lookup
                .SelectMany(l => l.Skip(n).Take(1))
                .ToList())
        .Where(xs => xs.Any())
        .ToList();

I get this:

result