Question

I'm trying to make a tracking algorithm, for this I need to constantly get the position of all the elements in the list, I want to know if there is a way to do it in a single line without a "ForEach", I know you can copy one whole list to another list, that is what I am doing right now.

I have this:

List copy = List original;

But I want to do something like this

List copy = List original.Position

Note: position is a vector2 var inside my list.

Was it helpful?

Solution

I would recommend using Linq:

List<Position> copy = original.Select(e => e.Position).ToList();

'e' I randomly chose, e stands for element. It represents each element in the list. This is the equivalent to:

List<Position> copy = new List<Position>();
foreach(Element e in original)
{
    copy.Add(e.Position);
}

This will return a List<Position>. Be aware that this List won't be of the same type as the original.

Also note that Linq queries, whilst clean, concise and easy to read, aren't as efficient as manually looping. However for a small list, a couple of hundred or less, you won't see any difference.

Here is a link to a very in depth SO question on this topic: foreach + break vs linq FirstOrDefault performance difference

And here is a link to using linq queries: http://msdn.microsoft.com/en-us/library/bb397906.aspx

In the example in the last link (to MSDN) you will see two forms of linq notation. One is the standard notation as I have used. The other is query form, which is similar to calling Where() using the standard notation. I find the query notation similar to writing SQL queries.

One final note is that you can also produce an array using ToArray() instead of ToList(). Preferable if the copy will be of a fixed size and you are going to randomly access them. Regardless of which you use, you can rely on the order of the copy to be the same as the original and that's how you should relate it to the original, so the 4th Position in copy is the Position of the 4th element in original for example.

I hope this has helped.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top