c# - 如何调用 IEnumerable 函数

标签 c# ienumerable

<分区>

我有这种功能。现在我不知道如何调用它来从字段中获取数据。

public static IEnumerable GetMaterialSearch(int reqNo)
    {
        DataClassesCRMDataContext dbContext = new DataClassesCRMDataContext();
        try
        {
            var res = from tbl1 in dbContext.MaterialApplicants
                      join tbl2 in dbContext.MaterialRequests on tbl1.ApplicantID equals tbl2.Applicant
                      where tbl2.RCD_ID == reqNo
                      select new
                      {
                          Crusher = tbl2.Crusher,
                          ApplicantID = tbl2.Applicant,
                          Comments = tbl2.Comments,
                          ReqDate = tbl2.ReqDate,
                          Operator = tbl2.Operator,
                          Title = tbl1.Title,
                          Applicant = tbl1.Applicant,
                          Address = tbl1.Address,
                          Nationality = tbl1.Nationality,
                          HouseNo = tbl1.HouseNo,
                          MobileNo = tbl1.MobileNo,
                      };

            if (res.Count() > 0)
            {
                return res.ToList();  
            }
            return null;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: " + ex.Message);
            return null;
        }
        finally
        {
            dbContext.Connection.Close();
        }
    }

最佳答案

IEnumerable 是一个通常用于迭代的序列:

var result = GetMaterialSearch(42);
if (result != null)
    foreach (var entry in result)
        DoSomething(entry);

编辑:正如上面所指出的,您的代码存在的问题是您在 IEnumerable 结果中返回了匿名类型。匿名类型无意跨越方法边界。来自 Anonymous Types (C# Programming Guide) :

You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. [...] To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. However, doing this defeats the purpose of strong typing. If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

如果您绝对不想创建命名类,您可以使用反射来访问您的字段,例如通过 C# 4 中引入的 dynamic 关键字:

var result = GetMaterialSearch(42);
if (result != null)
    foreach (dynamic entry in result)
        Console.WriteLine(entry.ID);

关于c# - 如何调用 IEnumerable 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18547900/

相关文章:

c# - 在 UI 线程上调用异步方法

c# - 使用 IEnumerable.Except

c# - 参数 IEnumerable<T> c#

c# - 使用 LINQ 过滤列表

c# - 将存储过程的结果作为 IEnumerable 返回

c# - 如何更改datagridview的值?

c# - 创建 Thickness() 时如何使用合格的 Double?

c# - 元素内容显示在设计时而不是运行时

c# - 如何修复电子邮件确认 - 在 .NET Core 中,它不起作用

c# - 在 IEnumerable 上使用 Observable 集合的优缺点