我正在尝试创建一个像这样的可重用方法
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.
最佳答案
您可以创建一个接口(interface)(在此示例中为IBusinessEntity
),该接口(interface)规定该项目必须具有如下所示的 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
并对该方法进行单元测试。
关于c# - 从具有多种用途对象的通用列表中选择或排序 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17368364/