Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can compare items of two lists with linq?

Tags:

c#

linq

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 main list.

like image 785
cagin Avatar asked Feb 10 '11 12:02

cagin


People also ask

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity. Now, how does it provide uniformity? Using a single LINQ query you can process data in various data sources.

What is any () in LINQ?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

Is LINQ good for performance?

It is slightly slowerLINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code. And if you'd like to measure the performance difference, you can use a tool like BenchmarkDotNet to do so.


2 Answers

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.

like image 159
Øyvind Bråthen Avatar answered Sep 20 '22 12:09

Øyvind Bråthen


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);
}
like image 35
Mehrad Avatar answered Sep 22 '22 12:09

Mehrad