Convert ToList() to a list of MyObject

时间:2015-05-12 23:27:38

标签: c# wpf linq list

I'm trying to convert a G of List that I'm doing operation on by using LINQ and turning back to a list of MyObject.

MyObject

So in another class I use that class to create a list of 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; } } objects via the database.

Part

After that I'm grouping them by description

List<Part> lstParts = DB.Query.GetParts();

EDIT:

var lstGrouped = lstParts.GroupBy(x => x.DescrFr);

How can I convert back the var lstGrouped = lstParts.GroupBy(x => x.PartNumber); back to lstGrouped? I have tried the List<Part> method and cast it to ToList(), it does not work, giving me an cast error:

enable to cast object of type

3 个答案:

答案 0 :(得分:1)

Since grouping returns an public class ComponentPrinter implements ComponentVisitor { public void printComponent(Component component) { component.acceptVisitor(this); } @Override public void visitComposite(Composite composite) { for (Component child : composite) { printComponent(component); } } @Override public void visitLeaf(Leaf leaf) { System.out.println("Found leaf: " + leaf); } } of IEnumerable you can't just transform it back into the sub-list. If you are trying to remove duplicates, just select the first one:

IGrouping

If you want all the items back (at which point, why did you group them?) then use List<Part> finalList = lstGrouped.Select(g => g.First()).ToList();

SelectMany

答案 1 :(得分:0)

GroupBy returns an function showPanel (panelId) { document.getElementById(panelId).classList.remove('panelHidden'); } so you are no longer working w/ just a list of IEnumerable<IGrouping<TKey, TSource>> (in your case TSource), 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).

答案 2 :(得分:0)

您希望从项目列表中获取不同的项目。在这种情况下,您可以在原始列表中使用Distinct方法,也可以使用组方法执行以下操作 -

lstParts.GroupBy(x =&gt; x.PartNumber).Select(x =&gt; x.First())。ToList();

相关问题