Home > Software engineering >  How to see if a the first varible of a List with custom class contain somthing?
How to see if a the first varible of a List with custom class contain somthing?

Time:07-27

So if it is a dictionary, I can check if the Key or Value contains something on its own. But if you have a list with a custom class. Things are different. In the script below, the dictionary is working properly since the wayspotAnchors.ID type is called Guid, and the key of a dictionary is Guid, so in Dictionary, it only compares if it contains the ID by using ContainKey.
However, when I use a List with a custom class. In the Custom class, it has more than one variable which allows my list to store many things.

The problem is when I compare the wayspotAnchors.ID with the List, it compares to everything that is stored in the list which creates an error because the second variable type in the custom list is not matching with the Guid only the first variable is. But there is no way to only compare the first variable of a custom List as Dictionary does.

  private void CreateAnchorGameObjects(IWayspotAnchor[] wayspotAnchors)
    {
        foreach (var wayspotAnchor in wayspotAnchors)
        {
            if (gameData_List.my_second_game_list.)
            {
                
            }
            if (_wayspotAnchorGameObjects.ContainsKey(wayspotAnchor.ID))
            {
                Debug.Log("working");
            continue;
            }
           

The custom class

public class MySecondGameList
{
    public Guid guid;
    public string readable_guid;
    public GameObject anchor_gameobject;
}

List of the custom class

public class GameData_List : MonoBehaviour
{
   
    public List<MySecondGameList> my_second_game_list;
}

The error enter image description here

CodePudding user response:

In stead of Contains you can use the Linq extension Any like this:

if (_wayspotAnchorGameObjects.Any(anchor => anchor.guid == wayspotAnchor.ID))

CodePudding user response:

You need to iterate over the list applying the Any extesion. The Any extension wants a lambda expression that returns a boolean value. If, during the enumeration, any lambda expression applied to the enumerated element, returns true then the whole Any expression returns true to your code

if (gameData_List.my_second_game_list.Any(x => x.guid == searchedGuid))
{
    // true

}
  • Related