如何从列表中获取不同的记录 [英] How to get distinct records from a list

查看:62
本文介绍了如何从列表中获取不同的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型为'Myclass`的列表

I have a list of type `Myclass`

List<Myclass> liSubjectIdDetail = new List<Myclass>();





其中Myclass看起来像



where Myclass looks like

public class  Myclass
  {
      public Nullable<decimal> SubjectId { get; set; }
      public string SubjectName { get; set; }
  }



我正在从表中添加记录到liSubjectIdDetail




I am adding records into liSubjectIdDetail from a table

foreach (decimal Id in VarCEMSIdDetail)
  {
      liSubjectIdDetail.AddRange(db.Stt.MyTable.Where(x => x.Id == Id).Select(x => new Myclass { SubjectId = x.SubjectId, SubjectName = x.SubjectName }).ToList());
  }





其中Id包含根据我获取的记录的某些ID的列表。



现在我想在此列表中只获得不同的记录。



我用哈希表代替List

我也尝试了



where Id contains a list of certain Ids on the basis of which records I fetch.

Now I want to get only distinct records in this list.

I have tried it with hashtable in place of List
and I also tried

liSubjectIdDetail= liSubjectIdDetail.Distinct().ToList();



但这也是行不通的。请给我一个更好的解决方案。

提前谢谢


but this too, is not working. Please give me a better solution.
Thanks in advance

推荐答案

嗯...它正在运行 - 只是不是你想象的方式应该。



它确实整理了所有不同的值,但是使用了默认的Comparer - 所以如果你还没有为你的类写一个Comparer它只会使用HashCode方法,它将返回所有记录 - 因为它们在某种程度上会有所不同!



如果你想通过你的类的属性使用Distinct(得到例如,所有具有不同SubjectName值的实例)然后你需要在调用Distinct时提供一个新的Comparer。

MSDN可以提供帮助: http://msdn.microsoft.com/en-us/library/bb338049.aspx [ ^ ]
Well...it is working - just not the way you think it should.

It is indeed sorting out all the distinct values, but using the default Comparer - so if you haven't written a Comparer for your class it will just use the HashCode method, which will return all the records - since they will be different in some way!

If you want to use Distinct by a property of your class (get all the instances that have different SubjectName values for example) then you need to supply a new Comparer when you do call Distinct.
MSDN can help: http://msdn.microsoft.com/en-us/library/bb338049.aspx[^]


这篇关于如何从列表中获取不同的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆