Projecting into KeyValuePair via EF / Linq

后端 未结 3 1165
长发绾君心
长发绾君心 2021-01-03 18:21

I\'m trying to load a list of KeyValuePairs from an EF / Linq query like this:

return (from o in context.myTable 
select new KeyValuePair

        
相关标签:
3条回答
  • 2021-01-03 18:27

    Select only columnA and columnB from your table, and move further processing in memory:

    return context.myTable
                  .Select(o => new { o.columnA, o.columnB }) // only two fields
                  .AsEnumerable() // to clients memory
                  .Select(o => new KeyValuePair<int, string>(o.columnA, o.columnB))
                  .ToList();
    

    Consider also to create dictionary which contains KeyValuePairs:

    return context.myTable.ToDictionary(o => o.columnA, o => o.columnB).ToList();
    
    0 讨论(0)
  • 2021-01-03 18:28

    There is also alternative, when you want to store multiple values for one key exists something what is called Lookup.

    Represents a collection of keys each mapped to one or more values.

    Here you have some official documentations.

    More over lookup seems to be much faster than Dictionary < TKey, List < TValue > >.

    0 讨论(0)
  • 2021-01-03 18:31

    Since LINQ to Entities does not support KeyValuePair, you should turns to LINQ to Object by using AsEnumerable first:

    return context.myTable
                  .AsEnumerable()
                  .Select(new KeyValuePair<int, string>(o.columnA, o.columnB))
                  .ToList();
    
    0 讨论(0)
提交回复
热议问题