C# 从列表中选择单个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/735248/
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
Select single item from a list
提问by Daniel
Using LINQ what is the best way to select a single item from a list if the item may not exists in the list?
如果列表中不存在该项目,使用 LINQ 从列表中选择单个项目的最佳方法是什么?
I have come up with two solutions, neither of which I like. I use a where clause to select the list of items (which I know will only be one), I can then check the count and make a Single call on this list if count is one, the other choice is to use a foreach and just break after getting the item.
我想出了两个解决方案,但我都不喜欢。我使用 where 子句来选择项目列表(我知道只有一个),然后我可以检查计数并在此列表上进行 Single 调用(如果计数为一),另一种选择是使用 foreach 并且只是拿到物品后休息。
Neither of these seem like a good approach, is there a better way?
这些似乎都不是一个好方法,有没有更好的方法?
采纳答案by Reed Copsey
You can use IEnumerable.First()
or IEnumerable.FirstOrDefault()
.
您可以使用IEnumerable.First()
或IEnumerable.FirstOrDefault()
。
The difference is that First()
will throw if no element is found (or if no element matches the conditions, if you use the conditions). FirstOrDefault()
will return default(T)
(null
if it's a reference type).
不同之处在于,First()
如果没有找到元素(或者如果没有元素匹配条件,如果使用条件),将会抛出异常。 FirstOrDefault()
将返回default(T)
(null
如果它是引用类型)。
回答by Denis Troller
Maybe I'm missing something here, but usually calling .SingleOrDefault()
is the way to go to return either the single element in the list, or a default value (null for reference or nullable types) if the list is empty.
It generates an exception if the list contains more than one element.
也许我在这里遗漏了一些东西,但通常调用.SingleOrDefault()
是返回列表中的单个元素或默认值(引用或可空类型为 null)(如果列表为空)的方法。如果列表包含多个元素,则会生成异常。
Use FirstOrDefault()
to cover the case where you could have more than one.
使用FirstOrDefault()
覆盖在那里你可以有一个以上的情况。
回答by bytebender
List<string> items = new List<string>();
items.Find(p => p == "blah");
or
或者
items.Find(p => p.Contains("b"));
but this allows you to define what you are looking for via a match predicate...
但这允许您通过匹配谓词定义您要查找的内容......
I guess if you are talking linqToSql then:
我想如果你在说 linqToSql 那么:
example looking for Account...
例如寻找帐户...
DataContext dc = new DataContext();
Account item = dc.Accounts.FirstOrDefault(p => p.id == 5);
If you need to make sure that there is only 1 item (throws exception when more than 1)
如果您需要确保只有 1 个项目(超过 1 个时抛出异常)
DataContext dc = new DataContext();
Account item = dc.Accounts.SingleOrDefault(p => p.id == 5);
回答by Samuel
There are two easy ways, depending on if you want to deal with exceptions or get a default value.
有两种简单的方法,具体取决于您是要处理异常还是获取默认值。
You can use the First<T>()
or the FirstOrDefault<T>()
extension method to get the first result or default(T)
.
您可以使用First<T>()
或FirstOrDefault<T>()
扩展方法来获得第一个结果或default(T)
。
var list = new List<int> { 1, 2, 4 };
var result = list.Where(i => i == 3).First(); // throws InvalidOperationException
var result = list.Where(i => i == 3).FirstOrDefault(); // = 0
回答by chakrit
Use the FirstOrDefault selector.
使用 FirstOrDefault 选择器。
var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var firstEven = list.FirstOrDefault(n => n % 2 == 0);
if (firstEven == 0)
Console.WriteLine("no even number");
else
Console.WriteLine("first even number is {0}", firstEven);
Just pass in a predicate to the Firstor FirstOrDefaultmethodand it'll happily go round' the list and picks the first match for you.
只需将谓词传递给First或FirstOrDefault方法,它就会很高兴地遍历列表并为您挑选第一个匹配项。
If there isn't a match, FirstOrDefault will returns the default value of whatever datatype the list items is.
如果不匹配,FirstOrDefault 将返回列表项的任何数据类型的默认值。
Hope this helps :-)
希望这可以帮助 :-)
回答by Marko
SingleOrDefault()
is what you need
SingleOrDefault()
是你需要的
cheers
干杯
回答by Brian Genisio
Just to complete the answer, If you are using the LINQ syntax, you can just wrap it since it returns an IEnumerable:
只是为了完成答案,如果您使用的是 LINQ 语法,则可以将其包装起来,因为它返回一个 IEnumerable:
(from int x in intList
where x > 5
select x * 2).FirstOrDefault()
回答by Uchenna Nnodim
just saw this now, if you are working with a list of object you can try this
现在才看到这个,如果你正在处理一个对象列表,你可以试试这个
public class user
{
public string username { get; set; }
public string password { get; set; }
}
List<user> userlist = new List<user>();
userlist.Add(new user { username = "macbruno", password = "1234" });
userlist.Add(new user { username = "james", password = "5678" });
string myusername = "james";
string mypassword = "23432";
user theUser = userlist.Find(
delegate (user thisuser)
{
return thisuser.username== myusername && thisuser.password == mypassword;
}
);
if (theUser != null)
{
Dosomething();
}
else
{
DoSomethingElse();
}