简体   繁体   中英

Linq add list inside a list in C#

I am working on adding a child model list inside a parent model list using linq. I got the parent and child model as the structure below.

public string A { get; set; }
public string B { get; set; }
public IEnumerable<ListItem> Childrens { get; set; }

I am manage to get some data for my parent model.

var Parent = 
    (from c in ExpenseCategorylist
     select new ListItem
     {
         A = c.Key,
         B = c.Value,
         Childrens = new List<ListItem>()
     }).ToList();

Now I am going to add data to the child model.

foreach(var c in Parent)
{
    var child= 
        (from d in ExpenseTypeList
        select new ListItem
        {
            A = d.Key,
            B = d.Value,
            Childrens = null,
        }).ToList();

c.Childrens.ToList().AddRange(child);
}


I am not able to update my parent model. Am I doing anything wrong?

As Alexey commented

c.Childrens.ToList().AddRange(child);

Will not add element to c.Childrens , but to a List created on the fly by .ToList() .

In order to do that you can either do:

testA.innerList= testA.innerList.Concat(data).ToList();

((List<int>)testA.innerList).AddRange(data);

With this simplify model for example:

public static void Main()
{
    var data = new []{1,2,3,4,5,6};

     var testA = 
         new TestA {
            Label="aa",
            innerList= new List<int>()
         };

    ///Err: IEnumerable doesn't contains AddRange
    //testA.innerList.AddRange(data);


    //as  Alexey commented
    testA.innerList= testA.innerList.Concat(data).ToList();
    testA.innerList.Dump();// Test:  Works
    testA.innerList=new List<int>(); //reset

    //Cast      
    ((List<int>)testA.innerList).AddRange(data);        
    testA.innerList.Dump();// Test:  Works  

    // With extention method
    testA.innerList.AddRange(data); 
    testA.innerList.Dump();// Test:  Works  
    testA.innerList=new List<int>(); //reset

}

public class TestA{
    public string Label {get; set;}
    public IEnumerable<int> innerList {get; set;}   
}

Live Demo

If AddRange on IEnumerable / ICollection / IList, you may consider writing an Extention method on IEnumerable.

public static void AddRange<T>(this IEnumerable<T> collection, IEnumerable<T> items)
{
  ((List<T>)collection).AddRange(items);    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM