I have a List of Foo.
我有一个Foo列表。
Foo has a string property named Bar.
Foo有一个名为Bar的字符串属性。
I'd like to use LINQ to get a string[] of distinct values for Foo.Bar in List of Foo.
我想使用LINQ在Foo列表中为Foo.Bar获取不同值的字符串[]。
How can I do this?
我怎样才能做到这一点?
4 个解决方案
#1
4
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()”等。
#2
3
This should work if you want to use the fluent pattern:
如果你想使用流畅的模式,这应该工作:
string[] arrayStrings = fooList.Select(a => a.Bar).Distinct().ToArray();
#3
2
Try this:
var distinctFooBars = (from foo in foos
select foo.Bar).Distinct().ToArray();
#4
0
Shouldn't you be able to do something like:
你不应该做这样的事情:
var strings = (from a in fooList select a.Bar).Distinct();
string[] array = strings.ToArray();
#1
4
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()”等。
#2
3
This should work if you want to use the fluent pattern:
如果你想使用流畅的模式,这应该工作:
string[] arrayStrings = fooList.Select(a => a.Bar).Distinct().ToArray();
#3
2
Try this:
var distinctFooBars = (from foo in foos
select foo.Bar).Distinct().ToArray();
#4
0
Shouldn't you be able to do something like:
你不应该做这样的事情:
var strings = (from a in fooList select a.Bar).Distinct();
string[] array = strings.ToArray();