分组列表<字符串>c# 中的类似类型字符串>
.GroupBy(x => x)
.GroupBy 用于对相似类型的 string、int 等进行分组。 那么我可以使用什么函数来对 List< 进行分组?字符串>类似类型的。
.GroupBy(x => x)
.GroupBy is used to group string,int,etc of similar types.
Then what function can i use to group List< string> of similar type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
GroupBy
依赖于以适当的方式实现Equals
/GetHashCode
的元素类型来实现您的目标。您的问题不清楚,但我的猜测是您希望两个具有相同元素的列表被视为相等。我怀疑您需要编写自己的
IEqualityComparer
实现,并将其传递到GroupBy
中。例如(未经测试):您还可以允许每个
ListEqualityComparer
实例具有单独的每个元素比较器,这将允许您以不区分大小写的方式比较(例如)字符串列表。GroupBy
relies on the element type implementingEquals
/GetHashCode
in an appropriate way for your aim.Your question isn't clear, but my guess is that you want two lists with the same elements to be considered equal. I suspect you'll need to write your own
IEqualityComparer
implementation, and pass that intoGroupBy
. For example (untested):You could also allow each
ListEqualityComparer
instance to have a separate per-element comparer, which would allow you to compare (say) lists of strings in a case-insensitive fashion.我假设您问如何按自定义类型的对象进行分组。
您需要定义如何将对象相互比较。
您可以通过在
GroupBy
调用中指定IEqualityComparer
来完成此操作。如果未指定
IEqualityComparer
,则使用IEqualityComparer.Default
,检查类型T
是否实现System.IEquatable
T>
接口,如果是,则返回使用该实现的EqualityComparer
。否则,它返回一个EqualityComparer
,它使用T
提供的 Object.Equals 和 Object.GetHashCode 重写。I assume you are asking how to group by objects of custom type.
You need to define how your objects should be compared to each other.
You can do this by specifying
IEqualityComparer
in theGroupBy
call.If you don't specify
IEqualityComparer
, thenIEqualityComparer.Default
is used, which checks whether typeT
implements theSystem.IEquatable<T>
interface and, if so, returns anEqualityComparer<T>
that uses that implementation. Otherwise, it returns anEqualityComparer<T>
that uses the overrides of Object.Equals and Object.GetHashCode provided byT
.