c# - Find an item in List by LINQ? -


Here I have a simple example to find an item in a list of strings. Generally I use it for a loop or anonymous rep:

  int GetItemIndex (string search) {int found = -1; If (_list! = Null) {foreach (string item in _list) // _list list & lt; String & gt; (Found ++; if (string.Equals (search, item)) {brake;}} / * used unknown string string foundItem = _list.Find (rep (string item) (found ++; return string .Elloles ( Search, item);}) returns;}  

LINQ is new to me. I'm curious if I can use LINQ to find items in the list?

There are a few ways (note it not a complete list) .

1) A single result I will return, but if one finds one or more (which is what you want or may be), then an exception throws:

  string search = "framework" ; & Lt; string & gt; MyList = New list of the list & lt; string & gt; (); string result = myList.Single (S => S == search);  

2) will return all the items that match your criteria, so that you can get an IEnumerable with an element:

  IEnumerable & lt; String & gt; Results = myList.Where (S => S == search);  

3) The first item matching your criteria will return:

  string result = myList.First (s = & gt; s == search );  

Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -