문제

I cannot seem to figure this one out. I found this on SO already, LINQ: grouping based on property in sublist. However, I must group Documents by multiple Name-Value pairs provided at runtime. Here are my types:

public class Document
{
    public string Name { get; set; }
    public List<Metadata> Metadata { get; set; }
}

public class Metadata
{
    public string Name { get; set; }
    public string Value { get; set; }
}

Now, if I have:

var groupableProperties = new List<string> { "Color", "Shape" };

var documents = new List<Document>()
{
    new Document()
    {
         Name = "sample.txt",
         Metadata = new List<Metadata>()
         {
             new Metadata() { Name = "Color", Value = "Red" },
             new Metadata() { Name = "Shape", Value = "Circle" },
             new Metadata() { Name = "Texture", Value = "Rough" }
         }
    },
    new Document()
    {
        Name = "sample2.txt",
        Metadata = new List<Metadata>()
        {
            new Metadata() { Name = "Color", Value = "Red" },
            new Metadata() { Name = "Shape", Value = "Circle" },
            new Metadata() { Name = "Texture", Value = "Smooth" }
        }
    },
    new Document()
    {
        Name = "sample3.txt",
        Metadata = new List<Metadata>()
        {
            new Metadata() { Name = "Color", Value = "Red" }
        }
    }
};

With groupableProperties provided at runtime, I would like to end up with 2 groups of Documents, Group 1: sample.txt, sample2.txt and Group 2: sample3.txt.

도움이 되었습니까?

해결책

A way to do this is

from d in documents
group d by string.Join("", d.Metadata
                            .Where(m => groupableProperties.Contains(m.Name))
                            .OrderBy (x => x.Name)
                            .Select(x => x.Value)
                      ) into g
select g;

This creates two groups, having keys RedCircle (sample.txt, sample2.txt) and Red (sample3.txt).

The ordering by name ensures that the key strings will always be the same when the names in groupableProperties are found.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top