LINQ-从对象层次结构中选择所有子级 [英] LINQ - Select all children from an object hierarchy
本文介绍了LINQ-从对象层次结构中选择所有子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个List
对象,其中包含一个字符串数组作为其属性之一.我想得到一个包含所有值的不同的字符串数组.
I have a List
of objects which contain a string array as one of their properties. I want to get a distinct string array containing all the values.
我的对象看起来像这样:
My object looks like this:
public class Zoo {
string Name { get; set;}
string[] Animals { get; set;}
}
有些动物园可能只有一种动物,有些可能有很多.为我提供List<Zoo>
中所有动物园中所有动物的唯一列表的最简单的Lambda表达式是什么?
Some zoos may have only one animal, some may have many. What would be the simplest Lambda expression or LINQ query to get me a unique list of all animals at all the Zoos in List<Zoo>
?
推荐答案
var query = zoos.SelectMany(zoo => zoo.Animals)
.Distinct();
或者,如果您是查询表达式迷(我不会这么简单):
Or if you're a query expression fan (I wouldn't be for something this simple):
var query = (from zoo in zoos
from animal in zoo.Animals
select animal).Distinct();
这篇关于LINQ-从对象层次结构中选择所有子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文