Joining IEnumerable <KeyValuePair <string, string >> values ​​into a string using Linq

Given IEnumerable<KeyValuePair<string,string>> , I'm trying to use linq to concatenate values ​​into one string.

My attempt:

 string path = attributes.Aggregate((current, next) => "@" + current.Key + "=" + current.Value + " and @" + next.Key + "=" + next.Value); 

This results in an error:

Cannot convert expression type ' string ' to return type ' KeyValuePair<string,string> '

Is there a more efficient way to do this in linq?

Full method ...

 public IEnumerable<XmlNode> GetNodes(IEnumerable<KeyValuePair<string,string>> attributes) { StateInfoXmlDocument stateInfoXmlDocument = new StateInfoXmlDocument(); string path = attributes.Aggregate((current, next) => "@" + current.Key + "=" + current.Value + " and @" + next.Key + "=" + next.Value); string schoolTypeXmlPath = string.Format(SCHOOL_TYPE_XML_PATH, path); return stateInfoXmlDocument.SelectNodes(schoolTypeXmlPath).Cast<XmlNode>().Distinct(); } 
+4
source share
4 answers

Is this what you are looking for?

 var strings = attributes.Select(kvp => string.Format("@{0}={1}", kvp.Key, kvp.Value)); string path = string.Join(" and ", strings); 
+11
source
 string s = String.Join("@",attributes.Select(kv=>kv.Key+"="+kv.Value)); 
+2
source

If you want to use an aggregate to create a string, you need to use a populated aggregate overload; if you use a version without seeding, then all types in the call must be the same.

0
source
 string templ = "{0}={1}"; string _authStr = String.Join("&", formParams.Select(kv => String.Format(templ, kv.Key, kv.Value)); 
0
source

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


All Articles