我需要从IDictionary<int,string>
的{{1}}匹配键中选择一个数据子集,然后返回一个新的IEnumerable<T>
。我陷入语法错误并得到错误:
方法
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;
}
作为dict
来过滤SubjectID
吗?
答案 0 :(得分:2)
好,因此这将返回与字典匹配的主题列表(其中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]
});
答案 1 :(得分:0)
尝试一个简单的yield
IEnumerable。 EG
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);