我正在尝试创建一个像这样的可重用方法
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(人员,员工等)。
请帮忙吗?
提前致谢。
L.I。
答案 0 :(得分:3)
您可以创建界面,在此示例中为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
和单元测试这个方法。
答案 1 :(得分:0)
感谢您的快速回答。我真的很感激。好吧,我看到了你的代码,我认为太棒了!我做了一个小应用程序来测试它,它有一些变化,因为一个接口不允许我定义公共属性和Order中的类型显示我的IBusinessEntity类型的冲突所以我宣布它除了订单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。