c# - 从具有多种用途对象的通用列表中选择或排序 C#

标签 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(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; }
}

因此,您的 PersonEmployee 类将更改为:

public class Person : IBusinessEntity
{
    public int ID { get; set; }
    // ...
}

public class Employee : IBusinessEntity
{
    public int ID { get; set; }
    // ...
}

然后您只允许传入业务实体(在本例中为 PersonEmployee),如下所示:

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/

相关文章:

c# - Lazy<T> 在处理异常时中断

c# - 测试这个有意义吗? (存储库模式)

list - Haskell中的递减范围

python - 如何在列表中每次运行连续零时删除除 x 之外的所有零?

java - 使用 Stream 从 String 消息中获取 ArrayList<String> 中的多个单词

java - 如何使用泛型实现类型安全?

java - 如何在接受 `Derived` 的重写方法中使用类型 `Base` 的参数?

c# - 在 Monotouch.Dialog 中设置 DateElement 的样式

c# - 如何使用 PartialView 在 ASP.Net MVC 的 webgrid 中绑定(bind)数据

java - 将类作为参数传递并返回相同的类对象