linq 中的区别?
我想知道如何才能实现这一目标?
我只想从对象集合中获取不同的名称,
MyObject a = new Object();
a.Name = 'One';
a.Value = '10';
MyObject b = new Object();
b.Name = 'One';
b.Value = '15';
MyObject c = new Object();
c.Name = 'Two';
c.Value = '10';
因此我只想获取名称。在这种情况下,我不关心值,只关心名称。
所以我尝试
//将所有对象添加到集合中。
myCollection.Disinct()..Select(x => new MyClassToStore() {Text = x.Name, Value = x.Name}).ToList());
但是,我需要在属性级别而不是在对象级别进行区分。所以我想要回“一”和“二”。现在我得到了“一”、“一”和“二”。
我看到一个名为 morelinq 的库,但我不确定是否应该使用它,因为它仍处于测试阶段并且似乎不再开发了。
再加上一个提取查询的整个库,我不确定它是否值得。
I am wondering how can I achieve this?
I want to get only distinct names from a collection of objects
MyObject a = new Object();
a.Name = 'One';
a.Value = '10';
MyObject b = new Object();
b.Name = 'One';
b.Value = '15';
MyObject c = new Object();
c.Name = 'Two';
c.Value = '10';
So I want to get only back the name. I don't care about the value in this case just the name.
So I tried
//add all the objects to a collection.
myCollection.Disinct()..Select(x => new MyClassToStore() {Text = x.Name, Value = x.Name}).ToList());
However I need to do distinct at the property level not at the object level. So I want back "One" and "Two". Right now I get "One", "One" and "Two" back.
I see a library called morelinq but I not sure if I should use it as it still in beta and does not seem to be developed on anymore.
Plus a whole library for one extract query I am not sure if it is worth it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也许这样的事情可以有所帮助?
Maybe something like this can help?
这将填充文本和值字段:
This populates both the Text and Value fields:
如果您只想返回不同的名称,您可以使用:
If you just want back distinct names, you can use:
您可以实现您的类,以便 linq 不同运算符不使用默认的相等比较器。
...您的实施细节。 ...
You can implement your class so the linq distinct operator does not use the default equality comparer.
... Your implementation details. ...
我个人建议您重写运算符 == 和 != 并确定对象如何以及为何是唯一的。然后对集合使用 Distinct() 调用。
您必须小心处理空值,请参阅 Microsoft 的 重载 Equals() 和运算符 == 的指南(C# 编程指南)。
Personally I suggest you override operator == and != and determine how and why an object is unique there. Then use the Distinct() call on the collection.
You do have to be careful with null values, see Microsoft's Guidelines for Overloading Equals() and Operator == (C# Programming Guide).