Is validation a string in one of the values ​​of a list property?

I have an open class.

public class StoreItems { public string itemName; public string itemPrice; public string itemQuantity; } 

I have a list.

 public List <StoreItems> itemData = new List<StoreItems> (); 

The user enters the name of the item, and they should check to see if that item name is in my itemData itemName.

My current code is something like this

 if (itemData.Find(x => x.itemData.Equals(userInput)) { //already in list } else { //add data } 

However, I get an error when itemData cannot be explicitly converted to bool. Tips will be appreciated

+5
source share
2 answers

You can easily achieve this with LINQ.

 if(itemData.Any(data => data.itemName == userInput)) 

Any checks all IEnumerable elements whether they match a given predicate or not.

+10
source

Since you have List<> and already tried to use List<T>.Find , this also works:

 StoreItems matchingItem = itemData.Find(si => si.itemName == userInput); if (matchingItem != null) { //already in list } else { //add data } 

Of course, this only works if there is no null reference in the list.

+3
source

Source: https://habr.com/ru/post/1269929/


All Articles