netmajor
netmajor

Reputation: 6585

other way to add item to List<>

In my other question You can see code of my arr structure and PriorityQueue collection. I normally add items to this collection like that:

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

I am curious that is other way to do this (add element(which is struct) object to List) ? In lambda way for example ? I just eager for knowledge :)

Upvotes: 1

Views: 2668

Answers (3)

garik
garik

Reputation: 5756

  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());

Upvotes: 2

Daniel Earwicker
Daniel Earwicker

Reputation: 116714

Another way is to use List.AddRange. It accepts an IEnumerable<T>, so you can pass it any collection of T, including arrays or the results of Linq expressions:

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

Upvotes: 3

Oded
Oded

Reputation: 499132

To add a new object to a list, you need to instantiate it.

The way you are doing it is correct, there is not lambda syntax or other syntactic sugar for this operation.

Upvotes: 4

Related Questions