Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: single list which consists of multiple properties of same type of object collection

 var userIds = books.Select( i => new{i.CreatedById,i.ModifiedById}).Distinct();

 var lst = from i in userIds select i.CreatedById;

 var lst1 = from i in userIds select i.ModifiedById;

 var lstfinal = lst.Concat(lst1).Distinct();

any other way to get same result???

here: books is collection of book objects i.e. IEnumerable.

thanks

like image 907
santosh ubale Avatar asked Aug 31 '25 03:08

santosh ubale


1 Answers

Alternative solution - SelectMany from array of required properties:

var lstfinal = books.SelectMany(b => new [] { b.CreatedById, b.ModifiedById })
                    .Distinct();

Or enumerating books collection twice. Union excludes duplicates, so you don't need to call Distinct (I'd go this way):

var lstfinal = books.Select(b => b.CreatedById)
                    .Union(books.Select(b => b.ModifiedById));
like image 133
Sergey Berezovskiy Avatar answered Sep 03 '25 03:09

Sergey Berezovskiy