※ This article uses int as an example, if you use a custom Datamodel, you need to actually use the Iequatable<t> interface.
1. Take intersection (A and b are both)
List A: {1, 2, 3, 5, 9}
List B: {4, 3, 9}
1 |
var intersectedList = list1.Intersect(list2); |
Outcome: {3, 9}
To see if A and b intersect.
1 |
boolisIntersected = list1.Intersect(list2).Count() > 0 |
2. Take the difference set (a Yes, B No)
List A: {1, 2, 3, 5, 9}
List B: {4, 3, 9}
1 |
var expectedList = list1.Except(list2); |
Results: {1, 2, 5}
Whether A and B have a difference set
1 |
boolisExpected = list1.Expect(list2).Count() > 0 |
3. Collecting the Union (contains a and b)
List A: {1, 2, 3, 5, 9}
List B: {4, 3, 9}
01 |
publicstatic classListExtensions |
03 |
publicstatic List<T> Merge<T>(thisList<T> source, List<T> target) |
05 |
List<T> mergedList = newList<T>(source); |
07 |
mergedList.AddRange(target.Except(source)); |
1 |
var mergedList = list1.Merge(list2); |
Results: {1, 2, 3, 5, 9, 4}
※6/15 supplement: Thank Rou torn greatly reminded that LINQ has built-in method union is desirable!
Language
Using LINQ, you can easily do a list's comparison,
If you have any questions, welcome to the discussion:)
Reproduced in: http://www.cnblogs.com/liguanghui/archive/2011/11/09/2242309.html
During the development process. The handling of arrays and collections is the most worrying. Some operations are typically handled with a for or foreach. Here are some commonly used sets and arrays of operation functions.
First, for example, 2 sets, A, B.
list<int> ListA = new list<int> {1,2,3,5,7,9};
list<int> Listb = new list<int> {13,4,17,29,2};
Lista.addrange (LISTB); Merges the collection a.b list<int> Result = lista.union (LISTB). Tolist<int> (); Reject duplicates list<int> Result = Lista.concat (LISTB). Tolist<int> (); Keep Duplicates
Lista.binarysearch ("1");//Determines whether a value is included in the collection. Returns 0 if included
In an example of two arrays
Int[] I=new int[]{1,2}; Int[] J=new int[]{2,3}; list<int> r = new list<int> ();
R.addrange (i);
R.addrange (j);
Int[] C = R.toarray (); Merging arrays
Int[] X=i.union (j). Toarray<int> (); Reject Duplicates
Int[] X=i.concat (j). Toarray<int> (); Keep Duplicates
int n = array.binarysearch (i,3);//Determines whether a value is included in the array. Returns 0 if included
C # intersection, list<t>, and difference sets for a set