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
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.
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.
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.
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With