Linq calls a function only once in a single expression

I am 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 this?

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

+6
source share
4 answers

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

 dict = fullGatewayResponse.Split(',') .Select(item => item.Split('=')) .ToDictionary(keySelector: parts => parts[0], elementSelector: parts => parts[1]); 
+12
source
 dict = (from item in fullGatetayResponse.Split(',') let pair = item.Split('=') select pair).ToDictionary(x => x[0], x => x[1]); 

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

 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); 
+8
source

Try the following:

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

This will work, but I don’t think it makes sense to keep split operations

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

Source: https://habr.com/ru/post/901427/


All Articles