I have list of int A,B. i like to do the following step in linq
list<int> c = new List<int>(); for (int i = 0; i < a.count; i++) { for (int j = 0; j < b.count; j++) { if (a[i] == b[j]) { c.add(a[i]); } } }
if its a and b is object
, I need check particular properties like this manner and add list if it equals how can i do this in linq?
eg a = {1,2,2,3} and b = {2,2,4,6} will give c = {2,2,2,2}. Is this what you want or are your lists unique anyway so its not important? I ask just because the obvious linq answer will give c={2,2} as that is the intersection of the lists.
Firstly, set two lists. List<int> val1 = new List<int> { 25, 30, 40, 60, 80, 95, 110 }; List<int> val2 = new List<int> { 27, 35, 40, 75, 95, 100, 110 }; Now, use the Intersect() method to get the intersection between two lists.
LINQ Intersect operator is used to find common elements between two sequences (collections). Intersect opertor comes under Set operators category in LINQ Query operators. For example, we have two collections A = { 1, 2, 3 } and B = { 3, 4, 5 }. Intersect operator will find common elements in both sequences.
Intersect returns the common elements of both entities and returns the result as a new entity. For example, there are two lists, the first list contains 1, 2 and 3 the and second list contains 3, 5 and 6. Then the intersect operator will return 3 as the result because 3 exists in both lists.
You could use the Intersect
method:
var c = a.Intersect(b);
This return all values both in a and b. However, position of the item in the list isn't taken into account.
You can use Intersect:
var a = new List<int>(); var b = new List<int>(); var c = a.Intersect(b);
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