这里我有一个简单的例子,在字符串列表中查找一个项。通常我使用for循环或匿名委托来这样做:
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 an anonymous delegate
string foundItem = _list.Find( delegate(string item) {
found++;
return string.Equals(search, item);
});
*/
}
return found;
}
LINQ对我来说是新的。我可以使用LINQ在列表中查找项目吗?如果这是可能的,怎么做?
如果你想要元素的索引,这将做到:
int index = list.Select((item, i) => new { Item = item, Index = i })
.First(x => x.Item == search).Index;
// or
var tagged = list.Select((item, i) => new { Item = item, Index = i });
int index = (from pair in tagged
where pair.Item == search
select pair.Index).First();
你不能在第一遍就消去。
注意,如果项目不存在,这将抛出。这通过使用可空int型来解决问题:
var tagged = list.Select((item, i) => new { Item = item, Index = (int?)i });
int? index = (from pair in tagged
where pair.Item == search
select pair.Index).FirstOrDefault();
如果你想要这个项目:
// 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;
不要忘记在这些情况下检查列表是否为空。
或者使用(list ??Enumerable.Empty<string>())而不是list。
如果你想要元素的索引,这将做到:
int index = list.Select((item, i) => new { Item = item, Index = i })
.First(x => x.Item == search).Index;
// or
var tagged = list.Select((item, i) => new { Item = item, Index = i });
int index = (from pair in tagged
where pair.Item == search
select pair.Index).First();
你不能在第一遍就消去。
注意,如果项目不存在,这将抛出。这通过使用可空int型来解决问题:
var tagged = list.Select((item, i) => new { Item = item, Index = (int?)i });
int? index = (from pair in tagged
where pair.Item == search
select pair.Index).FirstOrDefault();
如果你想要这个项目:
// 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;
不要忘记在这些情况下检查列表是否为空。
或者使用(list ??Enumerable.Empty<string>())而不是list。