使用Linq将IEnumerable<KeyValuePair<string,string>>值连接成字符串

6

给定 IEnumerable<KeyValuePair<string,string>>,我正在尝试使用 LINQ 将值连接成一个字符串。

我的尝试:

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

这会产生错误:

无法将表达式类型 'string' 转换为返回类型 'KeyValuePair<string,string>'

在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();
}
4个回答

18

这是您正在寻找的内容吗?

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

需要将 string.ToArray() 进行转换。 - bflemi3
@bflemi3,不支持.NET 4.0或更高版本 ;) - Thomas Levesque
好的,这解释了一切,我使用的是3.5版本 :) - bflemi3
@MatthewKennedy,因为在3.5及更早版本中没有接受IEnumerable<string>String.Join重载方法,它只接受数组。 - Thomas Levesque
@ThomasLevesque,我知道这一点,只是想知道为什么他不在4.0 / 4.1 / 4.5上。 - Matthew Kennedy
@MatthewKennedy,你并不总是能够自己选择...通常有商业原因需要你针对旧版本进行开发。 - Thomas Levesque

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

@Rawling 绝对不行,输出将会是 keyone=valueone@keytwo=valuetwo@keythree=valuethree - L.B
啊,对不起,你是正确的,情况不会那么糟糕,但仍然缺少“and”。 - Rawling

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

0
如果您想使用聚合函数来生成字符串,您需要使用带有种子值的聚合函数重载版本。如果您使用未带种子值的版本,则调用中的所有类型都需要相同。

那么,attributes.Aggregate("",(current, next) => current + " and @" + next.Key + "=" + next.Value); 但这会产生 and @zone=4 and @state=MD。如何拼接以使得开头不出现 'and '? - bflemi3
你可以使用Select将其转换为字符串,然后进行聚合操作(或使用其他答案提供的join静态方法)。 - megakorre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接