[英]How do I create a LINQ query to produce a unique list of objects from arrays inside object fields?
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.对于 package object,我需要在 package 中包含的每个文件中包含所有签名者对象的单个数组。
Currently, I am using this code to achieve the same result, but think this can be simplified and improved using LINQ.目前,我正在使用此代码实现相同的结果,但认为可以使用 LINQ 简化和改进。
foreach(var file in files) {
holder.AddRange(file.signers);
}
holder.Select(x => x).Distinct();
You could use SelectMany
to essentially flatten the signers in to a single list.您可以使用SelectMany
基本上将签名者扁平化到一个列表中。
There's also no need to do .Select(x => x)
it is essentially a no-op.也没有必要做.Select(x => x)
它本质上是一个空操作。
holder
.AddRange(files.SelectMany(file => file.signers))
.Distinct();
Using a HashSet as suggested by @Selvin as HashSets cannot contain duplicate entries and therefore no need for any equivalent to Distinct()
按照@Selvin 的建议使用 HashSet,因为 HashSet 不能包含重复的条目,因此不需要任何等同于Distinct()
的东西
// Earlier
HashSet<T> holder;
holder.UnionWith(files.SelectMany(file => file.signers));
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.