如果问题标题令人困惑,请提前致歉。我将尝试用一个例子来解释,希望它会很清楚。
我有一个像下面这样的类:
class A
{
Dictionary<string,string> myDict;
}
我想使用一些输入创建一个包含上述(例如:列表)的类列表,该输入将是以下类型的另一个列表:
class input
{
public string elem1;
public string elem2;
public string elem2;
public string elem2;
}
Ex: List<input> inputList;
我使用如下所示的 foreach 循环完成了相同的操作。我想知道,如果我能以更好的方式使用 LINQ 完成相同的任务:
var result = new List<A>();
foreach (var l in inputList)
{
var r = new A();
r.myDict.Add("elem1",l.elem1);
r.myDict.Add("elem1",l.elem1);
r.myDict.Add("elem1",l.elem1);
r.myDict.Add("elem1",l.elem1);
result.Add(r);
}
最佳答案
使用 linq 很容易做到,
input ip = new input();
Dictionary<string, string> myDictionary = typeof(input).GetFields(BindingFlags.Instance | BindingFlags.Public).ToDictionary(x => x.Name, x => x.GetValue(ip).ToString());
关于c# - 使用 LINQ 将类的字段复制到字典列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54199239/