[英]IEnumerable<T> to IDictionary<U, IEnumerable<T>>
[英]Select subset from IDictionary based on IEnumerable<T> and return IEnumerable<T>
我需要从IEnumerable<T>
的IDictionary<int,string>
匹配键中选择数据的子集,然后返回新的IEnumerable<T>
。 我陷入语法并得到错误:
无法从用法中推断方法
Extensions.GetValues<K, V>(IDictionary<K, V>, IEnumerable<K>)
的类型参数。 尝试显式指定类型参数。
这是我的代码:
public class Subject
{
public short SubjectID { get; set; }
public byte CategoryID { get; set; }
public string Title { get; set; }
}
public static class Extensions
{
public static IEnumerable<V> GetValues<K, V>(this IDictionary<K, V> dict, IEnumerable<K> keys)
{
return keys.Select((x) => dict[x]);
}
}
private IEnumerable<Subject> Translate()
{
IEnumerable<Subject> selectedSubjects = new Subject[] { new Subject { SubjectID = 1, CategoryID = 2, Title = null } };
// this is given externally as an IDictionary
var dict = new Dictionary<int, string>
{
{ 1, "Hello" },
{ 2, "Goodbye" }
};
// this line produces the error:
IEnumerable<Subject> data = dict.GetValues(selectedSubjects);
// would like to return IEnumerable<Subject> containing SubjectID = 1, CategoryID and Title = "Hello"
return data;
}
我想我需要告诉它使用SubjectID
short
地过滤dict
。
好的,因此这将返回与字典匹配的主题列表(其中dict.key == Subject.SubjectID
),从而更新Subject.Title = dict.value
:
return dict.Keys.Join(
selectedSubjects,
k => k,
s => (Int32)s.SubjectID,
(k, s) => new Subject
{
SubjectID = s.SubjectID,
CategoryID = s.CategoryID,
Title = dict[k]
});
尝试简单的IEnumerable yield
。 例如
public static IEnumerable<V> GetValues<K, V>(this IDictionary<K, V> dict, IEnumerable<K> keys)
{
foreach (var key in keys)
{
if (dict.TryGetValue(key, out V value))
{
yield return value;
}
}
}
然后是这样的:
var selectedSubjectIds = selectedSubjects.Select(s => s.SubjectID);
IEnumerable<Subject> data = dict.GetValues(selectedSubjectIds);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.