Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ - Union() the Group()-results

I have a list of Objects, where every object has a "Name" and different other stuff. I want to filter out those objects who don't have a unique name in that List.

Is there a LINQ Statement where I can "Union()" all the resulting groups and just return a IEnumerable of my objects?

Like

IEnumerable<MyObject> Results = (from x in Objects 
                                 group x by x.Name into g
                                 where g.Count() > 1
                                 select g)
                                 .COMBINE_OR_WHATEVER();

Thanks!

like image 518
Jens Avatar asked Apr 18 '12 12:04

Jens


2 Answers

Yes, there is. You can use SelectMany.

IEnumerable<MyObject> Results = (from x in Objects 
                                 group x by x.Name into g
                                 where g.Count() > 1
                                 select g)
                                 .SelectMany(x => x);
like image 60
Mark Byers Avatar answered Oct 06 '22 18:10

Mark Byers


I think you want only the object with unique names ("I want to filter out those objects who don't have a unique name in that List"):

var result = Objects.GroupBy(o => o.Name)
            .Where(grp => grp.Count() == 1)
            .SelectMany(grp => grp); 
like image 34
Tim Schmelter Avatar answered Oct 06 '22 19:10

Tim Schmelter