Home > Mobile >  How do I create a LINQ query to produce a unique list of objects from arrays inside object fields?
How do I create a LINQ query to produce a unique list of objects from arrays inside object fields?

Time:12-08

I have a series of file objects that have an array of signer objects as a field. For a package object, I need to include a single array of all the signer objects inside each file contained in a package.

Currently, I am using this code to achieve the same result, but think this can be simplified and improved using LINQ.

foreach(var file in files) {    
   holder.AddRange(file.signers); 
} 
holder.Select(x => x).Distinct();

CodePudding user response:

Try this,

files
 .Select(file => file.signers) //For each file in files return the file.signers prop
 .SelectMany(signers => signers) //Flatten the multiple enumerables of signer to one enumerable of strings
 .Distinct()
 .ToArray(); // Cast enumerable to Array

CodePudding user response:

You could use SelectMany to essentially flatten the signers in to a single list.

There's also no need to do .Select(x => x) it is essentially a no-op.

holder
  .AddRange(files.SelectMany(file => file.signers))
  .Distinct();

HashSet version

Using a HashSet as suggested by @Selvin as HashSets cannot contain duplicate entries and therefore no need for any equivalent to Distinct()

// Earlier
HashSet<T> holder;

holder.UnionWith(files.SelectMany(file => file.signers));
  • Related