Reputation: 85
I'm trying to convert a List
of MyObject
that I'm doing operation on by using LINQ and turning back to a list of MyObject
.
public class Part
{
public string ID { get; set; }
public string DescFr { get; set; }
public string DescEng { get; set; }
public string PartNumber{ get; set; }
public Part(string strID, string strDescFr, string strDescEng, string strPartNumber)
{
this.ID = strID;
this.DescFr = strDescfr;
this.DescEng = strDescEng;
this.PartNumber= strPartNumber;
}
}
So in another class I use that class to create a list of Part
objects via the database.
List<Part> lstParts = DB.Query.GetParts();
After that I'm grouping them by description
var lstGrouped = lstParts.GroupBy(x => x.DescrFr);
EDIT:
var lstGrouped = lstParts.GroupBy(x => x.PartNumber);
How can I convert back the lstGrouped
back to List<Part>
?
I have tried the ToList()
method and cast it to List<Part>
, it does not work, giving me an cast error:
enable to cast object of type
Upvotes: 0
Views: 1621
Reputation: 714
Looks like you want to get distinct items from the list of items. In that case you can either use Distinct method on the original list or you can go with your group approach and do the following -
lstParts.GroupBy(x => x.PartNumber).Select(x=>x.First()).ToList();
Upvotes: 0
Reputation: 61369
Since grouping returns an IEnumerable
of IGrouping
you can't just transform it back into the sub-list. If you are trying to remove duplicates, just select the first one:
List<Part> finalList = lstGrouped.Select(g => g.First()).ToList();
If you want all the items back (at which point, why did you group them?) then use SelectMany
List<Part> finalList = lstGrouped.SelectMany(g => g).ToList();
Upvotes: 1
Reputation: 4401
GroupBy returns an IEnumerable<IGrouping<TKey, TSource>>
so you are no longer working w/ just a list of TSource
(in your case Part
), but a list of groupings.
You may want to iterate over the groupings and get the list from each (see How to get values from IGrouping).
Hard to fully answer since I'm not clear on objective (why you would group, just to get the ungrouped list again).
Upvotes: 0