-1

I have two List in which color IDs are stored. I need to compare List adress1PlayerColorList and List bufferPropertyList and if there are the same values, then increase the variable int SameColorsCount. For example, I have two identical values in adress1PlayerColorList and bufferPropertyList, how can I make it so that after checking two Lists, my SameColorsCount value gives the number of identical elements?

        int adress1PlayerColor = new int();
        List<int> adress1PlayerColorList = new List<int>();
        for (int i = 0; i < adress1Player.Count; i++)
        {
            adress1PlayerColor = boardInstance.PropertyColor(adress1Player[i]);
            adress1PlayerColorList.Add(adress1PlayerColor);
            
        }

        ArrayList bufferProperty = playerManager.RequestPlayerProperties(indexNextPlayer);
        List<int> bufferPropertyList = new List<int>();
        int PlayerOwnPropertyColor = new int();
        for (int i = 0; i < bufferProperty.Count; i++)
        {
            PlayerOwnPropertyColor = boardInstance.PropertyColor((int)bufferProperty[i]);
            bufferPropertyList.Add(PlayerOwnPropertyColor);
            

        }
  • I've removed the `[visual-studio]` tag because this question isn't about using the Visual Studio application, and I've removed the `[unity3d]` tag because nothing in this question relates to Unity. – ProgrammingLlama Nov 23 '21 at 12:35
  • 1
    [FYI](https://stackoverflow.com/a/31069992/3181933). – ProgrammingLlama Nov 23 '21 at 12:36
  • 1
    What are you trying to do? Where did these values come from? If you have to compare lists of objects you may be able to use `IntersectBy` instead of extracting the object IDs – Panagiotis Kanavos Nov 23 '21 at 12:45
  • @PanagiotisKanavos I have a List A and List B - which stores the color IDs. I receive a request from List A, I have to check how many identical colors there are in List A and List B and output their number – Yama Lomama Nov 23 '21 at 12:51

1 Answers1

2

You can use Enumerable.Intersect to find the common items in any IEnumerable<T>, not just lists. LINQ provides methods for all set operations like Except, Intersect, Union, Concat :

var common =list1.Intersect(list2);

Intersect and the other set operations depended on object equality to determine whether two items match. That's OK for a List<int> but not very helpful for eg a Player class where equality depends on an Id.

IntersectBy

.NET(Core) 6 introduced IntersectBy and other similar methods that allow you to specify a property to compare for equality, eg :

var common=players1.IntersectBy(players2,x=>x.Id);

This means that instead of eg extracting the color IDs from a List<Color> to find the common colors, you can now use :

var commonColors=firstPlayer.Colors.IntersectBy(secondPlayer.Colors,x=>x.Id);
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236