Home > database >  C# Select List Containing Element Equaling Value
C# Select List Containing Element Equaling Value

Time:03-24

I have a QuickType JSON repository where I save data that I grab from an API. I've figured out how to loop through the list showing elements from each "entry", however I have a hard time figuring out how to select a specific entry that contains a specific value for a property.

Example: I have a list

public List<Robot> Robots

The class Robot is as following (showing only a few properties):

public partial class Robot
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("activity_text")]
    public string ActivityText { get; set; }
}

The API contains data for two Robots. After I receive the data from the API, I would have two different lists, and both of these lists have their own values for each property.

My question is, how would I select a list depending on, for example, which ID the list contains? If the JsonProperty ID equals 1 I select the specific list which contains the ID I was looking for, since I would need the values for that specific Robot's ID.

I've used this code previously to loop through the lists and output the information in each one:

foreach (var robots in result.Result.Robots)
{
    Console.WriteLine("Robot ID: "   robots.Id);
    Console.WriteLine("Activity: "   robots.ActivityText);
}

How would I go about this? I feel like my brain is fried from all of the Googling.

CodePudding user response:

This expands on what Paul commented, but as you said you don't know what that code does.

I will try to show you with code and comments:

// Get the first robot where Id equals to "1", if it exists
var matchingRobot = result.Result.Robots.FirstOrDefault(r => r.Id == "1");
// Check if the matchingRobot exists
if(matchingRobot != null){
    // Now we know it exists, we can access the property ActivityText
    Console.WriteLine("Robot with Id 2 has activity text: "   matchingRobot.ActivityText);
}
else{
    // The robot does not exist
    Console.WriteLine("There is no robot with Id 2");
}
  • Related