很抱歉这个问题,我不能造出这个句子。这是我的资料,
class Brand{
int ModelId;
string name;
}
class Gallery{
IList<Brand> brands;
...
public BrandList{
get{ return brands; }
}
}我有一个画廊的名单。像这样,
IList<Gallery> galleries;而且画廊中的每个画廊都有许多品牌。例如,图库中有6个图库对象。每个画廊都有自己的品牌。像这样,
Gallery1.Brandlist => Audi, Ford
Gallery2.BrandList => Mercedes,Volvo
Gallery3.BrandList => Subaru
Gallery4.BrandList => Renault
Gallery5.BrandList => Subaru
Gallery6.BrandList =>我试图通过LINQ获得的是一个品牌列表,这些品牌只与上面的第一个品牌截然不同(所以我不会选择福特和沃尔沃,即使它们在列表中)。画廊不一定要在他们的列表中有一个品牌。因此,它可能作为Gallery6为空。输出应该是,
{Audi, Mercedes, Subaru, Renault}我不知道如何使用LINQ来做到这一点。我尝试过SelectMany,但我对LINQ所能做的只是简单的(p=>p.Something = (int) something).ToList()。我想不出该怎么做。
发布于 2012-12-20 16:04:20
这应该是可行的:
var brands = galleries.Where(x => x.BrandList.Any())
.Select(x => x.BrandList.First().Name)
.Distinct();如果希望结果是Brand对象的集合,而不是字符串,可以这样做:
var brands = galleries.Where(x => x.BrandList.Any())
.GroupBy(x => x.BrandList.First().Name)
.Select(g => g.First().BrandList.First());https://stackoverflow.com/questions/13967613
复制相似问题