-2

I have below query, but it has 2 foreach loops which i consider not good. How can i get distinct value from IEnumerable> object by using linq.

Below is the code i have written,

var floatingIds= subInfo.Ranges.Select(c => c.RangeIDs.Select(s=>s)).Distinct();
 var floatIds= new List<Guid>();
                foreach (var ids in floatingIds)
                    foreach (var id in ids)
                    {
                        if (!floatIds.Contains(id))
                        {
                            floatIds.Add(id);
                        }
                    }

I have this post, but still am not getting expected values, but the above code gives correct IDs How do I avoid using nested foreach statements by using lambda or linq in this scenario?

Community
  • 1
  • 1
Govind
  • 979
  • 4
  • 14
  • 45
  • 6
    And let the answers "you can use `SelectMany`" begin... – Ivan Stoev Dec 26 '15 at 16:43
  • @IvanStoev: Yeah.. answers involving LINQ should explain the concerned operator ( `SelectMany( )` in this case ) instead of just showing its use. – displayName Dec 26 '15 at 16:46
  • Friend, you may find http://stackoverflow.com/questions/958949/difference-between-select-and-selectmany and https://www.youtube.com/watch?v=9tgz3aVNblM useful. The idea is to make List of Lists a List – Ian Dec 26 '15 at 16:50
  • actually am wrong, what i have written using selectmany is working, reason is i was passing wrong set of values. Anyhow thanks – Govind Dec 26 '15 at 16:50
  • @IvanStoev: I understood. This is why I said that answers should _explain_ the concerned LINQ operators. There are numerous **demonstrations** of LINQ on SO but very few **explanations**. If answers will properly explain what is happening, eventually these questions will reduce in number and then there would be lesser questions saying -_"I have (read) this post, but still am not getting expected values..."_ just the way this question is saying. – displayName Dec 26 '15 at 17:12
  • 1
    @displayname u r correct – Govind Dec 26 '15 at 17:22

2 Answers2

1

You can use SelectMany to flatten the collection and get all distinct values without any foreach:

var floatIds = subInfo.Ranges
    .SelectMany(c => c.RangeIDs.Select(s=>s))
    .Distinct()
    .ToList();
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
-1
var floatIds = subInfo.Ranges
    .SelectMany(c => c.RangeIDs.Select(s=>s))
    .Distinct()
    .ToList();
youOkay
  • 1
  • 1