摘要:[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):
string search = "lookforme";
List<string> myList = new List<string>();
string result = myList.Single(s => s == search);
2) Where will return all items which match your criteria, so you may get an IEnumerable with one element:
IEnumerable<string> results = myList.Where(s => s == search);
3) First will return the first item which matches your criteria:
string result = myList.First(s => s == search);
4) If it really is aList<string>
you don't need LINQ, just use:int GetItemIndex(string search) { return _list == null ? -1 : _list.IndexOf(search); }
5) If you are looking for the item itself, try:
string GetItem(string search) { return _list == null ? null : _list.FirstOrDefault(s => s.Equals(search)); }
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 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:
// 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();
If you want to count the number of items that match:
int count = list.Count(item => item == search);
// or
int count = (from item in list
where item == search
select item).Count();
If you want all the items that match:
var items = list.Where(item => item == search);
// or
var items = from item in list
where item == search
select item;