6

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

My Attempt:

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

This produces the error:

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

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

The 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

4 回答 4

17

这是你要找的吗?

var strings = attributes.Select(kvp => string.Format("@{0}={1}", kvp.Key, kvp.Value));
string path = string.Join(" and ", strings);
于 2012-10-19T20:33:07.133 回答
4
string s = String.Join("@",attributes.Select(kv=>kv.Key+"="+kv.Value));
于 2012-10-19T20:33:41.350 回答
0

如果你想使用聚合来创建一个字符串,如果你使用非种子版本,则需要使用聚合的种子重载,那么调用中的所有类型都必须相同。

于 2012-10-19T20:33:44.440 回答
0
string templ = "{0}={1}";
string _authStr = String.Join("&", formParams.Select(kv => String.Format(templ, kv.Key, kv.Value));
于 2015-06-23T11:55:43.820 回答