简体   繁体   中英

Linq call a function only once in one statement

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.

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

Try this:

dict = fullGatewayResponse.Split(',')
       .Select(y => y.Split('='))
       .ToDictionary(y => y[0], x => x[1]) 

This will work but I don't think there is any point in saving a split operation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM