performance 如何从内存列表中获取一组不同的属性值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40465/
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 get an array of distinct property values from in memory lists?
提问by Dane O'Connor
I have a List of Foo.
我有一个 Foo 列表。
Foo has a string property named Bar.
Foo 有一个名为 Bar 的字符串属性。
I'd like to use LINQto get a string[] of distinctvalues for Foo.Bar in List of Foo.
我想使用LINQ为Foo 列表中的 Foo.Bar获取不同值的字符串 [] 。
How can I do this?
我怎样才能做到这一点?
回答by chakrit
I'd go lambdas... wayyy nicer
我会去 lambdas ......更好
var bars = Foos.Select(f => f.Bar).Distinct().ToArray();
works the same as what @lassevk posted.
与@lassevk 发布的内容相同。
I'd also add that you might want to keep from converting to an array until the last minute.
我还要补充一点,您可能希望在最后一分钟之前避免转换为数组。
LINQ does some optimizations behind the scenes, queries stay in its query form until explicitly needed. So you might want to build everything you need into the query first so any possible optimization is applied altogether.
LINQ 在幕后做了一些优化,查询保持其查询形式,直到明确需要。因此,您可能希望首先将您需要的所有内容构建到查询中,以便完全应用任何可能的优化。
By evaluation I means asking for something that explicitly requires evalution like "Count()" or "ToArray()" etc.
通过评估,我的意思是要求明确需要评估的东西,例如“Count()”或“ToArray()”等。
回答by Guy
This should work if you want to use the fluent pattern:
如果您想使用流畅的模式,这应该可以工作:
string[] arrayStrings = fooList.Select(a => a.Bar).Distinct().ToArray();
回答by Lasse V. Karlsen
Try this:
尝试这个:
var distinctFooBars = (from foo in foos
select foo.Bar).Distinct().ToArray();
回答by Lasse V. Karlsen
Shouldn't you be able to do something like:
你不应该能够做这样的事情:
var strings = (from a in fooList select a.Bar).Distinct();
string[] array = strings.ToArray();

