Search code examples
c#linqjoinienumerablexelement

Perform Inner Join on 2 Files of type IEnumerable<XElement>


Lets say I have 2 files of type IEnumerable<XElement>. How would I perform an inner join and/or a group join on them? I have tried the following but the .Join method does not work on IEnumerable's. Any help would be appreciated.

var innerjoin = file1.Join(file2, c => file1.Elements("OrderID"), o => file2.Elements("OrderID"), (c, o) => new { Customer = c, Order = o });

Solution

  • Assuming that file1 and file2 contains IEnumerable<XElement> where each XElement has a child element OrderID, you can do join by OrderID value like this :

    var innerjoin = file1.Join(file2, 
                                c => (string)c.Element("OrderID"), 
                                o => (string)o.Element("OrderID"),
                                (c, o) => new {Customer = c, Order = o});
    

    Or using the equivalent query syntax :

    var innerjoin = from c in file1
                    join o in file2 
                       on (string)c.Element("OrderID") equals (string)o.Element("OrderID")
                    select new {Customer = c, Order = o};