Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a value exists in a list?

Tags:

c#

xml

I'm relatively new to C# programming (programming as a whole, actually), but I've built an application to manage the application pools on a server that my team at work uses. It does everything it's supposed to fairly well, but the only issue I'm running into is in saving previously-used configurations to the app.config file so the user doesn't have to put them in manually every time. As it stands, I can save to and load from the file magnificently (along with all of the strings I need in each group).

The issue is that I want to do a cursory check to see if a Name string exists in the group before writing it. Example of the part of the app.config:

<appSettings>
 <add Name="RowName" MachineName="MS-02348" AppSrvName="AppServer" WebSrvName="AppNet"/>
 <add Name="RowName2" MachineName="MS-68186" AppSrvName="AppServer2" WebSrvName="AppNet2"/>
</appSettings>

So what I'm currently doing to load the values is I have a method that retrieves the appSettings/add nodes and throws them into a list, then sets the values to properties of an object. The reason I do this is so that I can have a drop-down that lists only the Name of an object, and then the rest of the information is all available for when I call the method on the selected item.

Anyway, what I'm running into now is that I want to make sure that if the Name already exists in the app.config, I prompt the user to write another name instead of saving it to the database. Having two child nodes with the same "Name" value would wreak havoc on my logic.

I tried a foreach to cycle through the objects in the list, but without knowing how many objects there could be I didn't know of an easy way of really saying it does or does not exist. I've also tried targeting the childnode based on the values listed in the node, but it seems to fail there too. I'm guessing that part is syntax, but it seems to match up with how the method list defines it.

Any thoughts?

like image 590
hotleadsingerguy Avatar asked Dec 03 '22 20:12

hotleadsingerguy


1 Answers

if (list.Any()) 
{ 
   // found something! 
}
else 
{
   // found nothing 
}

I always use Any() simply because it's the most performant. List.Count() goes through each item and counts them, but you don't care about the number of items -- you only care if there's an item at all. Any() will enumerate through the list and stop if it finds an item. So, in the extreme case, in a list of a million items Count() will enumerate every single one and return while Any() will enumerate one and return.

Plus, it returns a bool, which is handy for more concise code. :)

As an added bonus, you can call Any() looking for specific things. So, in a list of people I can look to see if there are any people older than 21 in it:

if (list.Any(person => person.Age > 21))
{
   // ...
}

Edit: Formatting.

like image 140
Ari Roth Avatar answered Dec 16 '22 00:12

Ari Roth