Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking is string in one of the values of list property?

Tags:

c#

I have a public 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 will enter an item name and im supposed to check if that item name is already in my itemData's itemName.

My current code is something like this

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

However, I'm getting an error saying itemData cannot be implicitly converted to bool. Tips would be appreciated

like image 862
zoenightshade Avatar asked Jul 18 '17 07:07

zoenightshade


People also ask

How do you check if a string is in a list in JS?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check if a string is in a list C#?

Contains(T) Method is used to check whether an element is in the List<T> or not.

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .

How do you check if an object contains a string Java?

The Java String contains() method is used to check whether the specific set of characters are part of the given string or not. It returns a boolean value true if the specified characters are substring of a given string and returns false otherwise.


1 Answers

You can achieve this easily with LINQ.

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

Any checks all items of an IEnumerable whether they match a given predicate, or not.

like image 117
Tamás Szabó Avatar answered Oct 04 '22 21:10

Tamás Szabó