摘要:[LINQ] LINQ to Object 實例03 (LIST)
ref :http://stackoverflow.com/questions/1175645/find-an-item-in-list-by-linq
To find an item in a list of strings
Normally I use for loop or anonymous delegate to do it like this
int GetItemIndex(string search)
{
int found = -1;
if ( _list != null )
{
foreach (string item in _list) // _list is an instance of List<string>
{
found++;
if ( string.Equals(search, item) )
{
break;
}
}
/* use anonymous delegate
string foundItem = _list.Find( delegate(string item) {
found++;
return string.Equals(search, item);
});
*/
}
return found;
}
by other ways :
1) Single will return a single result, but will throw an exception if it finds none or more than one (which may or may not be what you want): 2) Where will return all items which match your criteria, so you may get an IEnumerable with one element: 3) First will return the first item which matches your criteria: 5)
If you are looking for the item itself, try: 6) Other options Do you want the item in the list or the actual item itself (would assume the item itself). Here are a bunch of options for you:string search = "lookforme";
List<string> myList = new List<string>();
string result = myList.Single(s => s == search);
IEnumerable<string> results = myList.Where(s => s == search);
string result = myList.First(s => s == search);
4)
If it really is a List<string>
you don't need LINQ, just use:
int GetItemIndex(string search)
{
return _list == null ? -1 : _list.IndexOf(search);
}
string GetItem(string search)
{
return _list == null ? null : _list.FirstOrDefault(s => s.Equals(search));
}
string result = _list.First(s => s == search);
string result = (from s in _list
where s == search
select s).Single();
string result = _list.Find(search);
int result = _list.IndexOf(search);
If you want the item: If you want to count the number of items that match: If you want all the items that match:// Throws if not found
var item = list.First(item => item == search);
// or
var item = (from item in list
where item == search
select item).First();
// Null if not found
var item = list.FirstOrDefault(item => item == search);
// or
var item = (from item in list
where item == search
select item).FirstOrDefault();
int count = list.Count(item => item == search);
// or
int count = (from item in list
where item == search
select item).Count();
var items = list.Where(item => item == search);
// or
var items = from item in list
where item == search
select item;