Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting distinct elements from two lists using LINQ?

Tags:

c#

linq

List<int> lst1 = new List<int>{1,2,3,5,2};
List<int> lst2 = new List<int>{4,5,6,1,6};
List<int> lst3 = new List<int>();

Expected Output: lst3={1,2,3,4,5,6}

Can anyone help me with the LINQ code to select distinct elements from two lists ?

Thank you

like image 449
Abishek Fernando Avatar asked Mar 10 '26 16:03

Abishek Fernando


1 Answers

Use the Union() method, which produces the Set Union of two lists, returning a new list containing all the items that exist in both lists:

lst3 = list1.Union(lst2).OrderBy(p=>p).ToList();
like image 200
Marek Woźniak Avatar answered Mar 13 '26 06:03

Marek Woźniak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!