Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing contents of a List<int> to find matches

For a bit of code I am writing, I have a method which checks a new object for similar properties with all existing objects.

This method returns a Dictionary<int, List<int>>. They key is the unique object ID, and the List contains the properties which are similar with the new object. (Constant.Name, Constant.StartDt, etc).

Now, there are several different types of matches which cannot occur. I need a way to compare the various combinations of matches to what is in these lists, and I need to be able to know which match has been matched.

Therefore, I was thinking of creating a List for each match, and comparing each list with the returned property list. However, I know I have done something similar before in Java and it had a flaw - it matched by order...I just need to know if each list CONTAINS these items.

so, two questions:

  1. Is this the best way to find the matches?
  2. If so, what is your suggested method of doing so? Loop through them? Or is there something built in to C# and I am not aware?
like image 377
Cody Avatar asked Jan 17 '26 22:01

Cody


1 Answers

You could use the LINQ Intersect method:

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx

        int[] id1 = { 44, 26, 92, 30, 71, 38 };
        int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };

        IEnumerable<int> both = id1.Intersect(id2);

        foreach (int id in both)
            Console.WriteLine(id);
like image 81
Jeff Avatar answered Jan 19 '26 17:01

Jeff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!