如何在 vb.net 中使用 Linq 选择单个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5358598/
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
How to select a single object using Linq in vb.net
提问by Hucker
I have done a lot of searching to what appears to be a simple LINQ problem but I can't figure out how to do grab an object out of a collection that has a specified minimum (or max value) without resorting to a sort like this:
我已经对看似简单的 LINQ 问题进行了大量搜索,但我无法弄清楚如何从具有指定最小值(或最大值)的集合中抓取一个对象,而无需求助于这样的排序:
dim customers= GetCustomers()
dim youngest = (From c in customers
Order By c.age Ascending).ToList.First
This (untested code) structure works fine with the exception that the entire customer array must be sorted and placed into a list for the only purpose of extracting the first value. That can't be the best way to get the minimum!
这种(未经测试的代码)结构工作正常,除了必须对整个客户数组进行排序并将其放入列表中才能提取第一个值。这不是获得最小值的最佳方法!
Note that I want the whole c record in this case, notthe minumum age of a customer that can be done like this (a typical example):
请注意,在这种情况下,我想要整个 c 记录,而不是可以像这样完成的客户的最小年龄(典型示例):
dim customers= GetCustomers()
dim youngest = (From c in customers
Select c.age).Min
Or even
甚至
dim customers= GetCustomers()
dim youngest = (From c in customers
Select c).Min(Function(x) x.age)
I can't for the life of me figure out how to get the whole object (or even the index) without resorting to the sort...
我一生都无法弄清楚如何在不求助于排序的情况下获取整个对象(甚至索引)......
回答by Sanjeevakumar Hiremath
Again, C# code, I'm not sure of I got it right in VB.NET
同样,C# 代码,我不确定我在 VB.NET 中是否正确
C#
C#
Customer youngest = customers.Aggregate((c1, c2) => (c1.age < c2.age) ? c1 : c2);
VB.NET
网络
dim youngest = customers.Aggregate( Function(ByVal c1, ByVal c2) IF( (c1.age < c2.age) , c1 , c2 ) );
回答by Snowbear
There is no such operator in regular LINQ which will avoid sorting of the entire IEnumerable
. But you're not the first one who needs a solution. For example check out Jason's answer here (though it's MaxBy
and C# but you'll get an idea): Simple LINQ question in C#
常规 LINQ 中没有这样的运算符可以避免对整个IEnumerable
. 但您不是第一个需要解决方案的人。例如,在这里查看 Jason 的答案(虽然它MaxBy
和 C# 一样,但你会得到一个想法):C# 中的简单 LINQ 问题
Or MinBy
from MoreLinq
或MinBy
来自MoreLinq
回答by DocMax
You are almost there. You should find that
你快到了。你应该发现
dim youngest = (From c in customers
Order By c.age Ascending
Select c).First
does what you are looking for. (I am a C# guy, not a VB.NET guy, so my syntax may be off a bit.)
做你正在寻找的。(我是一个 C# 人,不是 VB.NET 人,所以我的语法可能有点不对。)