How to group these XDocuments?

Problem

I have a collection of instances XDocument. Each document has a repeating element that can take on a different meaning. I want to group them by this value, but each element can specify a different value.

<sampledoc>
  <value>a</value>
  <value>b</value>
  <value>c</value>
</sampledoc>

Example

  • Document A has the values ​​a, b, c
  • Document B has values ​​b, c, d
  • Document C has values ​​a, b

I need a group that:

  • group a
    • Document A
    • Document C
  • group b
    • Document A
    • Document B
    • Document C
  • group c
    • Document A
    • Document B
  • group d
    • Document B

Question

I am sure I have to do this, but right now I do not see a tree for trees.

docs.GroupBy... ( ), , , , . , LINQ , , .

GroupBy AsLookup LINQ? ?

#, - .

Update

, :

// Collate all the different values
docs.SelectMany(doc => doc.Elements("Value")
                          .Select(el => el.Value))
    // Remove duplicate values
    .Distinct()
    // Generate a lookup of specific value to all
    // documents that contain that value
    .ToLookup(v => v, v => docs.Where(doc => doc.Elements("Value")
                                                .Any(el=>el.Value == v)));
+3
1

GroupBy , .

var docs = new XDocument[] { docA, docB, docC } ;
var result = docs
   .SelectMany(doc => doc.Root.Elements("Value"))
   .Select(el => el.Value)
   .Distinct()
   .Select(key => new {
        Key = key,
        Documents = docs.Where(doc =>
            doc.Root.Elements("Value").Any(el => el.Value == key))
   });
+3
source

Source: https://habr.com/ru/post/1713481/


All Articles