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
使用Union()
方法生成两个列表的Set Union,返回包含两个列表中存在的所有项的新列表:
lst3 = list1.Union(lst2).OrderBy(p=>p).ToList();
Basically, you can do
lst1.AddRange(lst2);
List<int> lst3 = lst1.Distinct().ToList();
Another approach (I think the most effcient one [amortized]):
var hashSet = new HashSet<int>(lst1);
foreach (var item in lst2)
{
hashSet.Add(item);
}
var lst3 = hashSet.ToList();
LINQ:
var lst3 = lst1.Union(lst2).ToList();
A basic approach
List<int> lst3 = new List<int>();
foreach (int x in lst1)
if (!lst3.Contains(x))
lst3.Add(x);
foreach (int x in lst2)
if (!lst3.Contains(x))
lst3.Add(x);
您可以使用UNION并从结果集中获取DISTINCT值
lst3 = lst1.Union(lst2).Distinct().ToList();
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.