2

質問について申し訳ありませんが、私は文を作成できませんでした。これが私が持っているものです、

class Brand{
    int ModelId;
    string name;
}

class Gallery{

    IList<Brand> brands;
    ...
    public BrandList{
        get{ return brands; }
    }
}

ギャラリーのリストがあります。このような、

IList<Gallery> galleries;

ギャラリーの各ギャラリーには多くのブランドがあります。たとえば、ギャラリーには6つのGalleryオブジェクトがあります。また、各ギャラリーにはブランドが含まれています。このような、

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()です。私はそれを行う方法を理解できませんでした。

4

2 に答える 2

4

使用SelectManyDistinct

IEnumerable<string> allUniqueBrands = allGalleries
    .SelectMany(g => g.BrandList.Select(b => b.Name)).Distinct();

クエリ構文の場合:

IEnumerable<string> allBrands = from gallery in allGalleries
                                from brand in gallery.BrandList
                                select brand.Name;
IEnumerable<string> allUniqueBrands = allBrands.Distinct();

編集:今私はそれを手に入れました、あなたは各ブランドリストの最初のブランドだけを必要とします。

を選択する場合は、で使用できるBrandカスタムを提供する必要があります。が必要な場合は、最後に電話してください。IEqualityComparer<Brand>DistinctList<Brand>ToList()

IEqualityComparer<Brand>for (またはUnion、 Intesect Distinct、Exceptなど)は次のとおりです。

public class BrandComparer : IEqualityComparer<Brand>
{
    public bool Equals(Brand x, Brand y)
    {
        if (x == null || y == null) return false;
        return x.Name.Equals(y.Name, StringComparison.OrdinalIgnoreCase);
    }

    public int GetHashCode(Brand obj)
    {
        if (obj == null) return int.MinValue;
        return obj.Name.GetHashCode();
    }
}

そしてここにすべての(最初の)ブランドの明確なリストがあります:

List<Brand> uniqueFirstBrands = allGalleries
    .Where(g => g.BrandList != null && g.BrandList.Any())
    .Select(g => g.BrandList.First())
    .Distinct(new BrandComparer())
    .ToList();
于 2012-12-20T08:03:36.017 に答える
3

これは機能するはずです:

var brands = galleries.Where(x => x.BrandList.Any())
                      .Select(x => x.BrandList.First().Name)
                      .Distinct();

結果を文字列ではなくブランドオブジェクトのコレクションにしたい場合は、次のようにすることができます。

var brands = galleries.Where(x => x.BrandList.Any())
                      .GroupBy(x => x.BrandList.First().Name)
                      .Select(g => g.First().BrandList.First());
于 2012-12-20T08:04:20.090 に答える