2

I need to iterate a list returned from a Dictionary by Linq. But, if I use ToList(), it becomes a List of a List.

Dictionary<Tuple<double, double>, List<Tuple<double, double>>> dict = new   Dictionary<Tuple<double,double>,List<Tuple<double,double>>>();
        Random rnd = new Random();
        for(int x =0; x < 3 ; ++x)
        {
             double a = rnd.NextDouble()*100;
             double b = rnd.NextDouble()*100;
             double c = Math.Ceiling(rnd.NextDouble()*100);
             double d = Math.Ceiling(rnd.NextDouble()*100);
             Tuple<double, double> tp = new Tuple<double, double>(c, d);
             List<Tuple<double, double>> ll = new List<Tuple<double,double>>();
             ll.Add(tp);
             c = Math.Ceiling(rnd.NextDouble() * 100);
             d = Math.Ceiling(rnd.NextDouble() * 100);
             tp = new Tuple<double, double>(c, d);
             ll.Add(tp);
             dict.Add(new Tuple<double, double>(a, b), ll);
        }

        var t = dict.Where(x => x.Key.Item1 == 50 || Math.Abs(x.Key.Item1 - 80) < 20).Select(x => x.Value);
        // if I used
        var t = dict.Where(x => x.Key.Item1 == 50 || Math.Abs(x.Key.Item1 - 80) < 20).Select(x => x.Value).ToList();
        // it became a list of list.
        foreach(var u in t)
        // here I cannot use u.item1 why? 
        // t is an Ienumerable of list<Tuple<double, double>>
        // if I used foreach(var u in t.Tolist())
        // it became a list of list.

Any help would be appreciated.

Tom Carter
  • 2,938
  • 1
  • 27
  • 42
user3601704
  • 753
  • 1
  • 14
  • 46

1 Answers1

6

Not too sure on your data structure but can you do this:

var t = dict.Where(x => x.Key.Item1 == 50 || Math.Abs(x.Key.Item1 - 80) < 20)
            .SelectMany(x => x.Value)
            .ToList();

Ultimately if you have collections nested, SelectMany basically collapses many collections into one. So in the case of your collections per Dictionary, it flattens them into one so instead of returning an IEnumerable for each element, it returns them as one nice collection :)

The example on MSDN is pretty nice, and explains how a collection of Objects, each with their own List<T>. So basically when we do the SelectMany it flattens the numerous collections into one which we can Select from.

Additional Resources

Difference Between Select and SelectMany

SelectMany on DotNetPerls

Community
  • 1
  • 1
JEV
  • 2,494
  • 4
  • 33
  • 47