Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ method How to SelectMany with additional column from Parent class

Tags:

c#

linq

I have a class :

public class Parent
{
    public int ParentID { get; set; }
    public string ParentName { get; set; }
    public List<Child> Childs { get; set; }
}

public class Child
{
    public int ChildID { get; set; }
    public string ChildName { get; set; }
}

With Parent object, here's how I get all Childs value.

Parent obj = GetParent();
PrintExcel(obj.SelectMany(sm => sm.Childs);

But I also want to include ParentName value in the select command, how to achieve this?

With SQL query, I can do this

SELECT
    p.ParentName,
    c.ChildName
FROM
    Parent p
    INNER JOIN Child c ON
        p.ParentID = c.ParentID
like image 315
warheat1990 Avatar asked Jun 28 '16 08:06

warheat1990


People also ask

What is the difference between the Select clause and SelectMany () method in Linq?

Select and SelectMany are projection operators. A select operator is used to select value from a collection and SelectMany operator is used to selecting values from a collection of collection i.e. nested collection.

What is the use of SelectMany in Linq?

The SelectMany<TSource,TResult>(IEnumerable<TSource>, Func<TSource,Int32,IEnumerable<TResult>>) method enumerates the input sequence, uses a transform function to map each element to an IEnumerable<T>, and then enumerates and yields the elements of each such IEnumerable<T> object.

What is select many?

SelectMany(<selector>) method The SelectMany() method is used to "flatten" a sequence in which each of the elements of the sequence is a separate, subordinate sequence.


1 Answers

Your LINQ example is flawed. Assuming you have a sequence of Parent (i.e. IEnumerable<Parent> or IQueryable<Parent>) called parents, you can access the parent inside the SelectMany at least in a two ways:

(A) Use Select inside the SelectMany:

parents.SelectMany(p => p.Childs.Select(c => new { p.ParentName, c.ChildName }))

(B) Use the SelectMany overload which allows you pass result selector:

parents.SelectMany(p => p.Childs, (p, c) => new { p.ParentName, c.ChildName })

And of course you can simply use the query syntax and let the compiler determine the correct method for you:

(from p in parents from c in p.Childs select new { p.ParentName, c.ChildName })
like image 181
Ivan Stoev Avatar answered Oct 17 '22 05:10

Ivan Stoev