38

Following code giving me 'Evaluation of lambda expressions is not valid in the debugger'. Please suggest where I am doing wrong from below -

List<MyFieldClass> lstFiedls;
lstFiedls = objDictionary.Select(item => item.Value).ToList();

Thanks,

Chris_web
  • 743
  • 3
  • 10
  • 19

3 Answers3

84

You don't need to use Linq to get the values. The Dictionary(TKey, TValue) has a property that holds the values, Dictionary(TKey, TValue).Values:

var fields = objDictionary.Values.ToList();
Dustin Kingen
  • 20,677
  • 7
  • 52
  • 92
  • 23
    It may be worth noting that the `ToList()` method of the `Dictionary.ValueCollection` class is actually an extension method in `System.Linq`. However, since the `ValueCollection` implements `ICollection` and `IEnumerable`, you can add the values to a list without converting. – LiquidPony Jul 22 '14 at 13:48
  • Also worth noting that you can use the `AsEnumerable()` Linq extension method to get an `IEnumerable` instead of a `List`. `objDictionary.Values.AsEnumerable()`. – RubberDuck Jan 04 '17 at 13:14
  • @RubberDuck is Values.AsEnumerable().GetEnumerator(); more performant than Values.ToList().GetEnumerator();? I am curious? – Gregory William Bryant Apr 20 '20 at 19:31
  • 1
    It’s just lazy @GregoryWilliamBryant. It won’t load the entire list as a copy into memory. A couple of benchmarks might be interesting. – RubberDuck Apr 20 '20 at 19:33
5

You will get a compiler error simply trying to convert a dictionary's values to a list with ToList():

        Dictionary<int, int> dict = new Dictionary<int, int>();
        var result = dict.Values.ToList();

Unless you include "using System.Linq" in your file.

Markus
  • 1,020
  • 14
  • 18
2

With C# 7 it is possible to use tuples, which makes this conversion much simpler and you can have both the key and the value in the list.

   var mylist = new List<(Tkey, TValue)>(dic.Select(x => (Tkey, TValue)));

full example

       Dictionary<int, string> dic = new Dictionary<int, string>();
        dic.Add(1, "test1");
        dic.Add(2, "test2");
        dic.Add(3, "test3");

        
        var mylist = new List<(int, string)>(dic.Select(x => (x.Key, x.Value)));

        foreach (var myItem in mylist)
        {
            Console.WriteLine($"int val = {myItem.Item1} string = {myItem.Item2}");
        }

result

int val = 1 string = test1
int val = 2 string = test2
int val = 3 string = test3
Stuart Smith
  • 1,931
  • 15
  • 26