简体   繁体   English

是否可以从 C# 中的通用对象集合中提取特定字段值的列表?

[英]Is it possible to pull out a list of particular field values from a collection of generic objects in C#?

I have the following method in a class I am using for pagination in my app:我在我的应用程序中用于分页的类中有以下方法:

public static PagedList<T> ToPagedList(IEnumerable<T> source, int pageNumber, int pageSize)
        {
            var count = source.Count();
            var items = source
              .Skip((pageNumber - 1) * pageSize)
              .Take(pageSize).ToList();

            return new PagedList<T>(items, count, pageNumber, pageSize);
        }

In this method I am passing in a collection of generic objects as IEnumerable<T> source which regardless of type will always have an Id field.在这种方法中,我将通用对象的集合作为IEnumerable<T> source传递,无论类型如何,它都将始终具有一个 Id 字段。 What I'd like to do is pull out all of the Ids for these objects and store them in a list to be passed into my PagedList constructor.我想做的是提取这些对象的所有 Id,并将它们存储在一个列表中,以传递给我的 PagedList 构造函数。 Is this possible?这可能吗?

Yes it is possible.对的,这是可能的。 You can use Reflection<\/a> to get the value of a property.您可以使用反射<\/a>来获取属性的值。

item.GetType().GetProperty("Id").GetValue(item, null);

the best way would be create an interface最好的方法是创建一个界面

public interface IBaseClass{
  public int Id {get; set;}
}

An interface would be the best way, but you specifically said "field" and interfaces cannot contain fields.接口将是最好的方法,但是您特别说“字段”并且接口不能包含字段。

You could get around this limitation with an abstract base class, but you cannot have multiple base classes on a single class (if applicable).您可以使用抽象基类来解决此限制,但您不能在单个类上拥有多个基类(如果适用)。

...All of this assumes that you have the ability to modify those classes. ...所有这些都假设您有能力修改这些类。

Another way to do this would be:另一种方法是:

public static PagedList<T> ToPagedList<T>(IEnumerable<T> source, int pageNumber, int pageSize)
{
    var count = source.Count();

    var items = source
        .Skip((pageNumber - 1) * pageSize)
        .Take(pageSize).ToList();

    var ids = items
        .Select(i => ((dynamic)i).Id)   // field is **always** named "Id"
        .Cast<int>()                    // its type is **always** int
        .ToList();
            
    return new PagedList<T>(items, count, pageNumber, pageSize/*, ids*/); // pass ids
}

This assumes the field in question is named "Id", and it is an int .这假设有问题的字段名为“Id”,并且它是一个int

Adjust accordingly and handle potential errors.相应地调整并处理潜在的错误。

I think I originally misunderstood the question, the comment by @Dusan caused me to reevaluate and update the code.我想我最初误解了这个问题,@Dusan 的评论让我重新评估和更新了代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM