RPM1984
RPM1984

Reputation: 73102

Help with C# LINQ Projection

I have a IQueryable<SomePOCO> (a LINQ-Entities query, if that matters):

public class SomePOCO
{
   public string ParentName { get; set; }
   public string Name { get; set; }
   public string Url { get; set; }
}

And i'm trying to project to a single object (anonymous type would be best, since i only need method scope) which has 2 properties:

public string ParentName { get; set; }
public ICollection<SimplePoco> { get; set; 

SimplePOCO is as follows:

public class SimplePOCO
{
   public string Name { get; set; }
   public string Url { get; set; }
}

The reason i'm doing this is that all of the "SomePOCO"s im retrieving have the same ParentName, so i just want that once, as opposed to bringing over the wire the same value N amount of times and doing a .First().

Hope that makes sense.

The end result is i should be able to do this:

var parentName = result.ParentName; // string
var pocos = result.SimplePOCOs; // ICollection<SimplePOCO>

I think i either need some kind of aggregation, like with GroupBy or SelectMany.

Any ideas?

Upvotes: 3

Views: 8650

Answers (2)

Bala R
Bala R

Reputation: 108937

I think you just need to do a group by Parent Name

var result = collection.GroupBy(i => i.ParentName)
           .Select(g => new {
                                ParentName = g.Key, 
                                SimplePocos = g.Select(i => new SimplePoco
                                                                {
                                                                 Name = i.Name, 
                                                                 Url = i.Url
                                                                 })
                              });  

Upvotes: 8

Daniel A. White
Daniel A. White

Reputation: 190897

This is the first step.

var groups = myQ.GroupBy(p => p.ParentName);

You will need to have your middle data structure. I'll call it Grouping.

var myList = new List<Grouping>();

foreach (var group in groups) {
   var newGrouping = new Grouping();
   new Grouping.ParentName = group.Key;
   newGrouping.SimplePocos = group.Select(p => new SimplePoco(p)).ToArray();
 }

You should have a constructor of SimplePoco that will convert it for you.

Upvotes: 3

Related Questions