从IEnumerable中检索数据?

时间:2012-03-01 05:56:04

标签: c# list ienumerable

[来自MSDN的CrossPost]

我有一个任务,我需要将一个通用List发送到一个方法,我需要迭代它并将其转换为Excel文件。我已经使用Data Table做了这个,但是使用Generic list我遇到了一些问题(我不想将我的通用列表转换为Data Table)。我将粘贴代码,帮助我找到答案。

我有两个通用列表

            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));
    }

当我将列表传递给Ienumerable时......我无法检索List IEnumerable列表中的数据。如果我检索数据,那么我可以进一步处理。任何人都可以向我推荐更好的主意吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

如果您需要访问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);
    }
}