将项目添加到List<>的其他方式

时间:2010-03-24 21:50:51

标签: c# list lambda

在我的other question中,您可以看到 arr 结构和 PriorityQueue 集合的代码。我通常会像这样添加项目到这个集合:

arr.PriorityQueue.Add(new element((value(item, endPoint) + value(startPoint, item)),item));

我很好奇,这是另一种方法(将元素(即struct)对象添加到List)?以lambda方式为例?我只是渴望知识:)

3 个答案:

答案 0 :(得分:4)

要将新对象添加到列表,您需要实例化它。

你这样做是正确的,这个操作没有lambda语法或其他syntactic sugar

答案 1 :(得分:3)

另一种方法是使用List.AddRange。它接受IEnumerable<T>,因此您可以传递T的任何集合,包括数组或Linq表达式的结果:

importantItems.AddRange(allItems.Where(item => item.IsImportant));

答案 2 :(得分:2)

  arrays arr = new arrays();
        arr.PriorityQueue = new List<element>(
            new [] { 
                new element {node = 1, priority =2 }, 
                new element { node = 2, priority = 10}
                //..
                //..
            });


        arrays arr2 = new arrays();
        arr2.PriorityQueue = new List<element>(
            arr.PriorityQueue
            );


        arrays arr3 = new arrays();
        arr3.PriorityQueue = new List<element>(arr2.PriorityQueue.FindAll(z => (1 == 1)));


        arrays arr4 = new arrays();
        arr4.PriorityQueue = new List<element>(arr3.PriorityQueue.ToArray());