我有以下代码,它创建了一个字典:
branches.ToDictionary(row => row.Field<object>(1), row => row.Field<object>(3)).ToList();
我想将字典值创建为row.Field<object>(3) + row.Field<object>(4)
。我想我正在寻找某种concat方法,但似乎没有一种方法可用。我是否必须单独遍历每个元素?
答案 0 :(得分:0)
只需连接它们,但如果这些是字符串列,请使用Field<string>
(首选)或ToString
:
branches.ToDictionary(
row => row.Field<object>(1),
row => row.Field<string>(3) + row.Field<string>(4))
.ToList();
通常使用正确的类型而不是object
。
如果只有对象,另一种方法是使用String.Concat
:
branches.ToDictionary(
row => row.Field<object>(1),
row => String.Concat(row.Field<object>(3), row.Field<object>(4)))
.ToList();
答案 1 :(得分:0)
如果row.Field<object>(3)
和row.Field<object>(4)
的类型为string
,请将其作为字符串阅读,并将+
一起阅读(或者使用string.Format
或{{ 1}}):
string.Concat
如果它们真的是branches.ToDictionary(
row => row.Field<object>(1),
row => row.Field<string>(3) + row.Field<string>(4)
).ToList();
或您只想要配对的两种类型,则可以将它们添加为元组,或者最好创建一个类来保存它们。例如:
object
然后将值投影到类中:
public class IntAndString //Choose a better name than this!
{
public int IntValue { get; set; }
public string StringValue { get; set; }
}