Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
RPM1984 Avatar asked Feb 17 '26 12:02

RPM1984


2 Answers

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
                                                                 })
                              });  
like image 179
Bala R Avatar answered Feb 19 '26 02:02

Bala R


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.

like image 35
Daniel A. White Avatar answered Feb 19 '26 00:02

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!