Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does the Select method do on a c# int array

Tags:

c#

I'm a beginner at C#.

I have come across this piece of code:

List<RelatedProductViewModel> relatedProductViewModel = vm.RelatedProductID.Select(p => new RelatedProductViewModel { RelatedProductID = p, ProductID = vm.ProductID, Type = vm.Type }).ToList();

vm.RelatedProductID is an int array with just one element (0) with a value of 8666.

So I'm thinking that Select is a method available on int arrays, but I can't find any documentation on this.

Can anybody enlighten me:

What does Select do?

Ultimately, I'm trying to figure out what value is being used for p in the llambda expression - please don't get too technical about llambda expression as I have only just read about them.

like image 261
Graham Avatar asked Dec 13 '25 23:12

Graham


2 Answers

Select creates a projection; meaning, you provide a function that takes an int and outputs a something, then for every int in the array it executes the function. It is basically this:

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

In your case, the selector for each is:

p => new RelatedProductViewModel { RelatedProductID = p,
                 ProductID = vm.ProductID, Type = vm.Type }

Meaning: each value p in the array become the RelatedProductID of a new RelatedProductViewModel, with a ProductID and Type set via the "captured" value of vm.

So the output in your example will be a list of length 1, where that single item has a RelatedProductID of 8666.

like image 179
Marc Gravell Avatar answered Dec 15 '25 11:12

Marc Gravell


Select is part of IEnumerable<T>. Arrays automatically implement IEnumerable<T> when they are created, so since it implements it, the .Select() is available from there.

But Select is projecting the results from one set to another. It is returning 1 result per iterated value.

When using .Select on an IQueryable<T>, internally it may work slightly differently. It retrieves them as they are iterated, much like a yield does.

By using ToList() at the end, you are forcing it to enumerate all results in one go. For in memory types this is quick, but for databases or resources that have a latency in retrieving items, this can have a large performance impact.

like image 33
Dominic Zukiewicz Avatar answered Dec 15 '25 13:12

Dominic Zukiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!