有没有什么好的方法可以使用LINQ确保多个集合具有相同的项目数?
试试这个:
bool sameLength = (collections.Select(c => c.Count())
.Distinct()
.Take(2) // Optional (for optimization).
.Count()) == 1;
或者:
bool sameLength = !collections.Select(c => c.Count()).Distinct().Skip(1).Any();
var collections = new List<ICollection> { a, b, c, d };
检查
如果collection1.Count() == collection2.Count()
请注意,这将枚举集合。如果集合枚举代价高昂(如LINQ2SQL)或会改变状态(更新一些数据和/或记录),那么使用LINQ就没有太好的方法。
ICollection
接口,你可以将它们放入一个单独的List<ICollection>
中,然后应用Mark的方法。var a = new List<int>();
var b = new List<double>();
var c = new List<float>();
var d = new List<string>();
var collections = new List<ICollection> { a, b, c, d };
var sameLength = collections.Select(c => c.Count).Distinct().Count() == 1;
.Distinct().Count() == 1
来代替。虽然会牺牲一些性能,但可读性会更好。.Skip(1).Any()
有点违反直觉。 - Dan AbramovICollection.Count
,如果集合数量较小,则不应有任何实质性的性能影响。但是当处理一些未知的集合时情况就不同了,这些集合只实现了IEnumerable<>
接口。我会修改代码。 - mgronber
.Distinct().Count() == 1
。我们会失去一些性能,但提高可读性。 - Dan Abramov