Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq call a function only once in one statement

Tags:

c#

.net

linq

I'm quite new to Linq. I have something like this:

dict = fullGatewayResponse.
Split(',').ToDictionary(key => key.Split('=')[0], value => value.Split('=')[1])

This works fine but for obvious reasons I don't want the split() method to be called twice. How can I do that ?

Thanks for all your responses :), but I can only choose one.

like image 307
Jonny Avatar asked Nov 14 '11 11:11

Jonny


2 Answers

You can convert each item to an array before ToDictionary by using Select:

dict = fullGatewayResponse.Split(',')
                          .Select(item => item.Split('='))
                          .ToDictionary(keySelector:     parts => parts[0],
                                        elementSelector: parts => parts[1]);
like image 156
dtb Avatar answered Oct 15 '22 16:10

dtb


dict = (from item in fullGatetayResponse.Split(',')
        let pair = item.Split('=')
        select pair).ToDictionary(x => x[0], x => x[1]);

or, if you want to keep the existence of the array hidden:

dict = (from item in fullGatetayResponse.Split(',')
        let pair = item.Split('=')
        select new{Key=pair[0],Value=pair[1]).ToDictionary(x=>x.Key,x=>x.Value);
like image 36
Marc Gravell Avatar answered Oct 15 '22 15:10

Marc Gravell