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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With