C# 在 LINQ 的列表中查找项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1175645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find an item in List by LINQ?
提问by David.Chu.ca
Here I have a simple example to find an item in a list of strings. Normally I use for loop or anonymous delegate to do it like this:
在这里,我有一个简单的示例来查找字符串列表中的项目。通常我使用 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 anonymous delegate
string foundItem = _list.Find( delegate(string item) {
found++;
return string.Equals(search, item);
});
*/
}
return found;
}
LINQ is new for me. I am curious if I can use LINQ to find item in list? How if possible?
LINQ 对我来说是新的。我很好奇我是否可以使用 LINQ 在列表中查找项目?可以的话怎么做?
采纳答案by Rex M
There's a few ways (note this is nota complete list).
有几种方法(注意这不是一个完整的列表)。
1) Singlewill 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):
1) Single将返回单个结果,但如果没有找到或多于一个(可能是也可能不是您想要的),则会抛出异常:
string search = "lookforme";
List<string> myList = new List<string>();
string result = myList.Single(s => s == search);
Note SingleOrDefault()
will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception.
Note 的SingleOrDefault()
行为相同,除了它会为引用类型返回 null,或为值类型返回默认值,而不是抛出异常。
2) Wherewill return all items which match your criteria, so you may get an IEnumerable with one element:
2) Where将返回符合您的条件的所有项目,因此您可能会获得一个包含一个元素的 IEnumerable:
IEnumerable<string> results = myList.Where(s => s == search);
3) Firstwill return the first item which matches your criteria:
3) First将返回符合您条件的第一个项目:
string result = myList.First(s => s == search);
Note FirstOrDefault()
will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception.
Note 的FirstOrDefault()
行为相同,除了它会为引用类型返回 null,或为值类型返回默认值,而不是抛出异常。
回答by R. Martinho Fernandes
If you want the index of the element, this will do it:
如果你想要元素的索引,这将做到:
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();
You can't get rid of the lambda in the first pass.
您无法在第一遍中摆脱 lambda。
Note that this will throw if the item doesn't exist. This solves the problem by resorting to nullable ints:
请注意,如果该项目不存在,这将引发。这通过使用可为空的整数来解决问题:
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();
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;
And don't forget to check the list for null
in any of these cases.
并且不要忘记null
在任何这些情况下检查列表。
Or use (list ?? Enumerable.Empty<string>())
instead of list
.
或者使用(list ?? Enumerable.Empty<string>())
代替list
.
Thanks to Pavel for helping out in the comments.
感谢 Pavel 在评论中提供帮助。
回答by AgileJon
If it really is a List<string>
you don't need LINQ, just use:
如果它真的是List<string>
你不需要 LINQ,只需使用:
int GetItemIndex(string search)
{
return _list == null ? -1 : _list.IndexOf(search);
}
If you are looking for the item itself, try:
如果您正在寻找项目本身,请尝试:
string GetItem(string search)
{
return _list == null ? null : _list.FirstOrDefault(s => s.Equals(search));
}
回答by Kelsey
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);
回答by Will Marcouiller
I used to use a Dictionary which is some sort of an indexed list which will give me exactly what I want when I want it.
我曾经使用一个字典,它是某种索引列表,它会在我想要的时候准确地给我想要的东西。
Dictionary<string, int> margins = new Dictionary<string, int>();
margins.Add("left", 10);
margins.Add("right", 10);
margins.Add("top", 20);
margins.Add("bottom", 30);
Whenever I wish to access my margins values, for instance, I address my dictionary:
例如,每当我希望访问我的边距值时,我都会处理我的字典:
int xStartPos = margins["left"];
int xLimitPos = margins["right"];
int yStartPos = margins["top"];
int yLimitPos = margins["bottom"];
So, depending on what you're doing, a dictionary can be useful.
因此,根据您在做什么,字典可能会很有用。
回答by RckLN
This method is easier and safer
这种方法更简单更安全
var lOrders = new List<string>();
bool insertOrderNew = lOrders.Find(r => r == "1234") == null ? true : false
bool insertOrderNew = lOrders.Find(r => r == "1234") == null ? true : false
回答by Colonel Panic
How about IndexOf
?
怎么样IndexOf
?
Searches for the specified object and returns the index of the first occurrence within the list
搜索指定的对象并返回列表中第一次出现的索引
For example
例如
> var boys = new List<string>{"Harry", "Ron", "Neville"};
> boys.IndexOf("Neville")
2
> boys[2] == "Neville"
True
Note that it returns -1 if the value doesn't occur in the list
请注意,如果该值未出现在列表中,则返回 -1
> boys.IndexOf("Hermione")
-1
回答by brinch
Here is one way to rewrite your method to use LINQ:
这是重写您的方法以使用 LINQ 的一种方法:
public static int GetItemIndex(string search)
{
List<string> _list = new List<string>() { "one", "two", "three" };
var result = _list.Select((Value, Index) => new { Value, Index })
.SingleOrDefault(l => l.Value == search);
return result == null ? -1 : result.Index;
}
Thus, calling it with
因此,调用它
GetItemIndex("two")
will return 1
,
GetItemIndex("two")
会回来1
,
and
和
GetItemIndex("notthere")
will return -1
.
GetItemIndex("notthere")
会回来-1
。
Reference: linqsamples.com
回答by Nayeem Mansoori
Try this code :
试试这个代码:
return context.EntitytableName.AsEnumerable().Find(p => p.LoginID.Equals(loginID) && p.Password.Equals(password)).Select(p => new ModelTableName{ FirstName = p.FirstName, UserID = p.UserID });
回答by befree2j
This will help you in getting the first or default value in your Linq List search
这将帮助您在 Linq 列表搜索中获得第一个或默认值
var results = _List.Where(item => item == search).FirstOrDefault();
This search will find the first or default value it will return.
此搜索将找到它将返回的第一个值或默认值。