从IEnumerable检索数据

本文关键字:数据 检索 IEnumerable | 更新日期: 2023-09-27 18:26:19

[CrosPost From MSDN]

我有一个任务,我需要向一个方法发送一个通用列表,在那里我需要迭代它并将其转换为Excel文件。我已经在数据表中做到了这一点,但在泛型列表中,我面临着一些问题(我不想将泛型列表转换为数据表)。我将粘贴有助于我得到答案的代码。

我有两个通用列表

            List<User>       objList = new List<User>();
            List<Student> objStudent = new List<Student>();

//我正在添加一些项目到列表

            User obj = new User(1, "aaa");
            User obj1 = new User(2, "bbb");
            User obj2 = new User(3, "ccc");
            User obj3 = new User(4, "ddd");

            Student sobj = new Student(1, "aaa");
            Student sobj1 = new Student(2, "bbb");
            Student sobj2 = new Student(3, "ccc");
            Student sobj3 = new Student(4, "ddd");
            objList.Add(obj);ExportToExcel(objList);

要将其导出到Excel,我将列表作为传递给以下方法

    public void ExportToExcel<T>(IEnumerable<T> list)
    {
        PropertyInfo[] piT = typeof(T).GetProperties();
        var Users = list.ToList();
        Type myType = (typeof(T));
    }

当我把我的清单传给Ienumable时。。。我无法检索List IEnumerable列表中的数据。如果我检索到数据,那么我可以进一步处理。有人能给我提个更好的主意吗?

从IEnumerable检索数据

如果您总是使用List<T>,您可以将IEnumerable<T>更改为IList<T>。AFAIK IEnumerable接口没有定义访问集合内部数据的方法,只是对其进行迭代

如果ICollection<T>适合您的需要,您甚至可以使用它。

如果需要访问类型T上所有属性的值,可以使用PropertyInfo.GetValue方法:

public void ExportToExcel<T>(IEnumerable<T> items)
{
    var properties = typeof(T).GetProperties();
    foreach(var item in items)
    {
        foreach(var property in properties)
        {
            var value = property.GetValue(item, null);
            // Do something else with the property's value
        }
    }
}

编辑以回应评论

您表示可能会收到一个或多个列表。您可以添加另一个重载,它接受组合的列表,然后对其进行迭代并导出每个单独的列表:

public void ExportToExcel<T>(IEnumerable<IEnumerable<T>> itemSets)
{
    foreach(var itemSet in itemSets)
    {
        ExportToExcel(itemSet);
    }
}