【问题标题】:Iterate through a DataTable columns using lambda expression使用 lambda 表达式遍历 DataTable 列
【发布时间】:2017-07-13 07:44:00
【问题描述】:

我想使用 lambda 表达式遍历 DataTable 列。目前我正在尝试使用ForEach。下面是示例代码。

foreach (DataColumn x in registeredpeople.Columns)
{
    Response.Write(tab + x.ColumnName);
    tab = "\t";
}

我想实现这样的事情,我们可以通过列表的集合来实现。

exampleCollection.ForEach(x =>
{
    sample.ID = x.Value,
    sample.Name = x.Text
});

【问题讨论】:

  • 请问您为什么要这样做?为什么标准的foreach 不好?
  • @Magnus 不是因为foreach 不好。我只想在我的应用程序中保持一致性,我尽可能使用 lambda 表达式而不是 foreach。我觉得 lambda 表达式让代码更干净。
  • 您应该阅读 C# 编译器团队的 Eric Lippert 的看法:blogs.msdn.microsoft.com/ericlippert/2009/05/18/…

标签: c# linq lambda datatable


【解决方案1】:

ForEachList<T> 的一个方法,因此您必须将该集合转换为列表。但这真的值得努力吗?

registeredpeople.Columns  // returns a DataColumnCollection 
    .Cast<DataColumn>()   // needed because DataColumnCollection doesn't implement IEnumerable<T> but just the non-generic IEnumerable(its old) 
    .ToList()             // needed because you want to use a method of List<T>, created a new List and fills it in a loop
    .ForEach(col => Console.WriteLine(col.ColumnName));

当然foreach 效率更高,而ForEach 对您没有任何好处。

【讨论】:

    猜你喜欢
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 2019-08-03
    • 1970-01-01
    • 2010-09-08
    • 2014-05-16
    • 1970-01-01
    相关资源
    最近更新 更多