简体   繁体   English

Linq 在 C# 的列表中添加列表

[英]Linq add list inside a list in C#

I am working on adding a child model list inside a parent model list using linq.我正在使用 linq 在父 model 列表中添加子 model 列表。 I got the parent and child model as the structure below.我得到了父子 model 的结构如下。

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.我设法为我的父母 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.现在我要向子 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.我无法更新我的父母 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() .不会将元素添加到c.Childrens ,而是添加到由.ToList()创建的 List 中。

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:有了这个简化 model 例如:

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.如果在 IEnumerable / ICollection / IList 上添加范围,您可以考虑在 IEnumerable 上编写扩展方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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