Home > Back-end >  C# Can't Add to List of Objects (cannot convert date type)
C# Can't Add to List of Objects (cannot convert date type)

Time:11-24

I'm have 3 "BOMrow", which are added to "itemBOMList". Each "BOMrow" is a class, ParentChildPair. Then do groupby to the "itemBOMList", having "result". Finally I want to add the "result" to the master list, "BOMList". However, a error shows "cannot convert from 'System.Collections.Generic.List<<anonymous type: string Child, bool IsReferencePart, string Parent, int Quantity>>' to 'addToList.ParentChildPair'"

I tried to add .Cast<ParentChildPair>() before ToList(), but this does not work either, showing "cannot convert from 'System.Collections.Generic.List<addToList.ParentChildPair>' to 'addToList.ParentChildPair'". Please help.

class ParentChildPair
    {
        public string Parent { get; set; }
        public string Child { get; set; }
        public int Quantity { get; set; }
        public bool IsReferencePart { get; set; }
    }


    

 class Program
    {
        static void Main(string[] args)
    {
        List<ParentChildPair> itemBOMList;
        itemBOMList = new List<ParentChildPair>();

        List<ParentChildPair> BOMList;
        BOMList = new List<ParentChildPair>();

        List<ParentChildPair> newresult;

        //List<ParentChildPair> convertedResult;
        //convertedResult = new List<ParentChildPair>();

        ParentChildPair BOMrow = new ParentChildPair();

        BOMrow.Parent = "parent1";
        BOMrow.Child = "child1";
        BOMrow.Quantity = 1;
        BOMrow.IsReferencePart = false;
        itemBOMList.Add(BOMrow);

        BOMrow = new ParentChildPair();
        //BOMrow = null;

        BOMrow.Parent = "parent1";
        BOMrow.Child = "child2";
        BOMrow.Quantity = 1;
        BOMrow.IsReferencePart = false;
        itemBOMList.Add(BOMrow);

        BOMrow = new ParentChildPair();

        BOMrow.Parent = "parent1";
        BOMrow.Child = "child2";
        BOMrow.Quantity = 2;
        BOMrow.IsReferencePart = false;
        itemBOMList.Add(BOMrow);

        var result = itemBOMList.GroupBy(d => d.Child)
.Select(
    g => new
    {
        Child = g.Key,
        IsReferencePart = g.First().IsReferencePart,
        Parent = g.First().Parent,
        Quantity = g.Sum(s => s.Quantity)
    }).ToList();

        BOMList.Add(result);

    }
}

CodePudding user response:

Your linq query is returning IEnumerable of anonymous objects. You need to make an instance of ParentChildPair. Then you can add it to list, but you need use AddRange method because result of your query will be IEnumerable.

var result = itemBOMList.GroupBy(d => d.Child)
.Select(
    g => new ParentChildPair
    {
        Child = g.Key,
        IsReferencePart = g.First().IsReferencePart,
        Parent = g.First().Parent,
        Quantity = g.Sum(s => s.Quantity)
    }).ToList();

    BOMList.AddRange(result);
  • Related