如何使用LINQ使用泛型类型查询[key]属性?

问题描述 投票:1回答:1

假设我有一堂课:

public class Customer
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

现在我想创建一个通用的Get()方法,该方法可以查询Customer或也定义了[key]字段的其他几个类中的任何一个。

public T Get<T>(int id)
{            
    string json = DoSomething(); // <-- making it easy for this post
    List<T> items = JsonConvert.DeserializeObject<List<T>>(json);            
    return items.FirstOrDefault(i => i. ????? = id);
}

我不确定如何使用Linq通用地指定[key]字段。

谢谢!

c# .net
1个回答
0
投票

希望这会有所帮助:

public interface IBase
{
    int Id { get; }
}
public class Customer : IBase
{
    public string Name { get; set; }
    public int Id { get ; set ; }
}
public T Get<T>(int id) where T : IBase
{
    string json = DoSomething(); // <-- making it easy for this post
    List<T> items = JsonConvert.DeserializeObject<List<T>>(json);
    return items.FirstOrDefault(i => i.Id = id);
}

只需在所有其他类中实现接口IBase

© www.soinside.com 2019 - 2024. All rights reserved.