C# 从通用列表中选择或排序多用途对象C
我正在尝试创建一个像这样的可重用方法C# 从通用列表中选择或排序多用途对象C,c#,list,generics,select,C#,List,Generics,Select,我正在尝试创建一个像这样的可重用方法 public static void Order<T> (List<T> filteredList, List<T> fullList) { //Getting list of ID from all business entities. HashSet<long> ids = new HashSet<long>(filteredList.Select
public static void Order<T> (List<T> filteredList, List<T> fullList)
{
//Getting list of ID from all business entities.
HashSet<long> ids = new HashSet<long>(filteredList.Select(x => x.ID));
//Ordering the list
return fullList.OrderByDescending(x => ids.Contains(x.ID)).ThenBy(x => !ids.Contains(x.ID)).ToList();
}
因为我有多个做相同事情的对象,但它们是不同类型的集合。但很明显,问题出在x.ID上,因为ID是来自业务实体的属性。我是说。假设T是Person,ID是属性。但ID不能从通用列表中识别,我想做通用列表,因为我的所有业务实体都有ID Person、Employee等
需要帮忙吗
提前谢谢
L.I.您可以创建一个接口,在本例中为IBusinessEntity,该接口说明该项必须具有如下ID:
public interface IBusinessEntity
{
public int ID { get; set; }
}
因此,您的Person和Employee类将更改为:
public class Person : IBusinessEntity
{
public int ID { get; set; }
// ...
}
public class Employee : IBusinessEntity
{
public int ID { get; set; }
// ...
}
然后,您将只允许本例中的业务实体以如下方式传入Person和Employee:
public static void Order<IBusinessEntity> (List<IBusinessEntity> filteredList, List<IBusinessEntity> fullList)
{
//Getting list of ID from all business entities.
HashSet<long> ids = new HashSet<long>(filteredList.Select(x => x.ID));
//Ordering the list
return fullList.OrderByDescending(x => ids.Contains(x.ID)).ThenBy(x => !ids.Contains(x.ID)).ToList();
}
当然,这也允许您使用此方法创建模拟IBusinessEntity和单元测试。感谢您的快速回答。我真的很感激。我看到了你的代码,我认为这太棒了!我做了一个小应用程序来测试它,它有一些变化,因为接口不允许我定义公共属性,并且类型顺序显示了类型IBusinessEntity的冲突,所以我声明它为Order T。除此之外,它很棒。最后,这是最后的结果
public interface IEntity
{
int id { get; set; }
}
public class Person: IEntity
{
public int id { get; set; }
}
public class Employee : IEntity
{
public int id { get; set; }
}
public static List<IEntity> Order<T>(List<IEntity> filtered, List<IEntity> full)
{
HashSet<int> ids = new HashSet<int>(filtered.Select(x => x.id));
return full.OrderByDescending(x => ids.Contains(x.id)).ThenBy(x => !ids.Contains(x.id)).ToList();
}
多谢各位
L.I.检查答案是否正确取决于你自己。人们倾向于做的是,如果答案确实回答了问题,但是你发现其他问题,那就是将答案标记为正确,然后问另一个问题,详细说明下一个问题。当然是我的意见!所以,如果你觉得我的答案确实回答了你的问题,你可能会想把它标记为答案,然后发布另一个新的问题来解释你上面的问题。这样做的好处是,您的新问题将出现在新列表中,而在此处重新发布则没有人知道或能够提供帮助。