我有一本字典,它的类型为Dictionary<int, fooClass> fooDic
,另一个字典为Dictionary<int, string> barlist
,我使用此linq返回结果
var foobarList = fooDic.Where(kvp =>
!barlist.ContainsKey(((fooClass)kvp.Value)._fooID))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
这将返回fooDic类型的结果。但我需要输入转换输出为barlist(Dictionary<int, string>)
类型。怎么样?
答案 0 :(得分:2)
如果这是一个相当简单的转换,那么关键是
的最后一部分var foobarList = fooDic.Where(kvp =>
!barlist.ContainsKey(((fooClass)kvp.Value)._fooID))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
语句。您目前使用kvp => kvp.Value
的位置,将其替换为kvp => kvp.Value._foobarValue
。
根据OP的评论编辑“完整”解决方案。
答案 1 :(得分:1)
假设你的班级Foo看起来像这样:
public class Foo
{
public string SomeValue { get; set; }
public int SomeOtherStuff { get; set; }
}
创建一个新词典:
var fooDict = new Dictionary<int, Foo>() {
{0, new Foo() {SomeOtherStuff=10, SomeValue="some value"} },
{1, new Foo() {SomeOtherStuff=15, SomeValue="some other value"} }
};
转换它:
Dictionary<int, string> stringDict =
fooDict.ToDictionary(x=> x.Key, x=> x.Value.SomeValue); //<- note x.Value.SomeValue
stringDict现在将包含:
{0, "some value"}, {1, "some other value"}