代码之家  ›  专栏  ›  技术社区  ›  Sha Dean Kuga

基于IEnumerable<T>从IDictionary中选择子集并返回IEnumerable<T>

  •  0
  • Sha Dean Kuga  · 技术社区  · 6 年前

    我需要从 IDictionary<int,string> 匹配来自 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 short 不知怎么的?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Camilo Terevinto Chase R Lewis    6 年前

    好的,这将返回一个与字典匹配的主题列表(其中 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] 
        });
    
        2
  •  0
  •   David Browne - Microsoft    6 年前

    尝试一个简单的 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);