Reputation: 2711
I have a List<List<int>>
with the following values:
[1] = 1,2
[2] = 4,5,6
[3] = 1,3
What I want to do is to retrieve simple List with unique values => 1,2,3,4,5,6 (number one was duplicated in original list).
If it was 1D List, I would use
variable.Select(n=>n).Distinct();
however when I tried to use
variable.Select(n=>n.Select(x=>x)).Distinct();
I got 2D list (with unique values I guess). How can I solve this? Thanks
Upvotes: 1
Views: 509
Reputation: 4816
You could do SelectMany
if you want a distinct of your overall integers, but if you want distinc lists, you could do something like this;
void Main()
{
List<List<int>> xss = new List<List<int>>()
{
new List<int>() {1, 2},
new List<int>() {1, 2},
new List<int>() {1, 2},
new List<int>() {4, 5, 6},
new List<int>() {1, 3}
};
xss.Select (x => string.Join(",", x)).Distinct();
}
Upvotes: 1
Reputation: 3060
private static void Main()
{
List<List<int>> xss = new List<List<int>>()
{
new List<int>() {1, 2},
new List<int>() {4, 5, 6},
new List<int>() {1, 3}
};
var xs = xss.SelectMany(x => x).Distinct();
Console.WriteLine(string.Join(" ",xs));
}
Upvotes: 1
Reputation: 101732
You could just use SelectMany
with Distinct
var uniqueList = list.SelectMany(x => x).Distinct().ToList();
SelectMany
flattents the List<List<int>>
into a IEnumerable<int>
and Distinct
eliminates the duplicates.
Upvotes: 8