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
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.
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));
}
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.