【发布时间】:2013-07-13 20:50:21
【问题描述】:
我遇到了一段我无法弄清楚甚至可能无法工作的代码。您可以在下面找到代码。
我试图在上下文中找出代码
GetDataTableData() 方法返回一个System.Data.DataTable,Select(...) 方法返回一个DataRow 对象数组:DataRow[] rows。据我所知, Select() 中的 lambda 无效。
var table = GetDataTableData()
.Select(s => new { s.Index })
.AsEnumerable()
.Select(
(s, counter) => new { s.Index, counter = counter + 1 }
);
我的问题:这个 lambda 有什么作用 - 它是否有效/有效?
Select(...) 方法有几个重载,它们都以字符串类型开头。
- lambda 表达式可以是字符串类型吗?
- 什么是 lambda 的返回类型 - 总是一个委托?
这里是上面有问题的行
// of what type is this (a delegate?)
s => new { s.Index }
...
// and what does this
(s, counter) => new { s.Index, counter = counter + 1 }
阅读以下答案后更新
据我了解,至少第二个 Select 指的是 IEnumerable.Select<T> 。但是在集合上调用 AsEnumerable() 不会改变底层类型:
// calling AsEnumberable() does not change type
IEnumerable<DataRow> enumDataRows = GetDataTable().AsEnumerable();
Type type = enumDataRows.GetType().GetGenericArguments()[0];
type.Dump(); // still returns DataRow
因此,要使 lambda 表达式 (s) => { return new { s.Index }; } 起作用,基础类型中必须存在 Index 属性。
这个假设正确吗?
关于第一次选择
我如何识别它是 Select() 中的构建或可枚举方法 Enumerable.Select<TSource, TResult>
-
IEnumerable<TSource>, Func<TSource, TResult>之一 - 或
IEnumerable<TSource>, Func<TSource, Int32, TResult>
尽管如此,我认为该语句仍然无效,因为 tSource 基础对象 DataRow 没有属性 Index:
var tResult = GetDataTable().Select(
(tSource, tResult) => { return new { tSource.Index }; }
);
这个假设正确吗?
【问题讨论】: