2012-10-19 24 views
4

給定IEnumerable<KeyValuePair<string,string>>,我嘗試使用linq將值連接成一個字符串。使用Linq將IEnumerable <KeyValuePair <string,string >>值連接到字符串中使用Linq

我嘗試:

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

這將產生錯誤:

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

有沒有更effiecient方式LINQ做到這一點?

完整的方法...

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(); 
} 

回答

11

這是你在找什麼?

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

所需轉換'string.ToArray()' – bflemi3

+0

@ bflemi3,而不是在.NET 4.0或更高版本) –

+0

很好解釋它,我在3.5 :) – bflemi3

2
string s = String.Join("@",attributes.Select(kv=>kv.Key+"="+kv.Value)); 
+0

@Downvoter你不喜歡什麼? –

+0

@Rawling絕對**沒有**,輸出將是'keyone = valueone @ keytwo = valuetwo @ keythree = valuethree' –

+0

Aaah對不起,你是對的,它不會那麼糟糕,但它仍然錯過了「和「S。 – Rawling

0

如果你想使用總讓你需要的,如果你在通話使用沒有接種版本,那麼所有類型使用的骨料 的種子超載的字符串必須是相同的。

+0

所以然後'attributes.Aggregate(「」,(current,next)=> current +「和@」+ next.Key +「=」+ next 。值);但是,這會產生...'和@ zone = 4和@ state = MD'。如何連接這樣'和'不會出現在開頭? – bflemi3

+0

你使用Select來讓它們以字符串開始,然後聚合(或者使用其他答案給出的連接靜態方法) – megakorre

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