开发者

how can compare items of two lists with linq?

开发者 https://www.devze.com 2023-02-09 13:15 出处:网络
I have two lists and one of them has 5 elements and the other one has 4 elements. They have some same elements but they have different elements too. I want to create a list with their different elemen

I have two lists and one of them has 5 elements and the other one has 4 elements. They have some same elements but they have different elements too. I want to create a list with their different element. How can i do it?

Note: 5 elements list is my m开发者_JS百科ain list.


What about this?

var list1 = new List<int>( new []{1,2,3,4,5});
var list2 = new List<int>( new []{1,3,4});
var list3 = list1.Except( list2);

In this case, list3 will contain 2 and 5 only.

EDIT

If you want the elements from both sets that are unique, the following code should suffice:

var list1 = new List<int>( new []{1,2,3,4,5});
var list2 = new List<int>( new []{1,3,4,7});
var list3 = list1.Except(list2).Union(list2.Except(list1));

Will output 2,5 and 7.


If you're curious, the opposite of this is called Intersect

string[] collection1 = new string[] { "1", "7", "4" };
string[] collection2 = new string[] { "6", "1", "7" };

var resultSet = collection1.Intersect<string>(collection2);

foreach (string s in resultSet)
{
    Console.WriteLine(s);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消