2

If I perform .Select() on a collection, will the resulting collection share exact index values between the two collections.

Perhaps I haven't explained myself well. Here's what I mean:

int[] nums = new int[]{ 50, 100, 200};

var moreNums = nums.Select(num => num / 2);

Will moreNums[0] = 25? [1] = 50? [2] = 100?

Can you bank on this, 100% of the time? I always feel a sense of ambiquity with LINQ because of this. This is important because I have two lists where I can use a single index to refer to a pair of values between the two lists. I don't want my lists to go out of sync.

Joe Shanahan
  • 816
  • 5
  • 21

3 Answers3

6

Select method logic is really simple: it takes one element at a time from you source collection, applies selector function and yields the result. That feature is called deferred execution - elements are fetched from source collection one at a time when they are needed and returned right after that.

Select could be written as follows:

public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
    foreach(var item in source)
    {
        yield return selector(source);
    }
}

As you can see, there is no way to get items in different order using only Select method!

In practice the method looks a little bit more complicated, but the logic is exactly the same.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

Yes it alwasy give the result you expected
I had done this code and it always work

List<decimal> MyList = new List<decimal>() { 10,20,30,40};
var Output= MyList.Select(s => s / 2).ToList();

Result in Output is

5  
10
15
20
Amit Bisht
  • 4,870
  • 14
  • 54
  • 83
-1

25 50 100 in case 1.

0 50 100 in case 2.

0 50 100 in case 3. not 5 50

int[] nums = new int[]{ 50, 100, 200};

var moreNums = nums.Select(num => num / 2);

// case 1
foreach (var item in moreNums) Console.Write("{0} ", item);
Console.WriteLine();

// case 2
nums[0] = 0;

foreach (var item in moreNums) Console.Write("{0} ", item);
Console.WriteLine();

// case 3
nums = new int[]{ 10, 100 };

foreach (var item in moreNums) Console.Write("{0} ", item);
Console.WriteLine();
user3093781
  • 374
  • 3
  • 6