[英]Convert foreach to LINQ statement
linq expresson是做什么用的? 我不知道如何將foreach語句更改為linq表達式。
public static IList<T> ToList<T>(this System.Data.DataTable table, Dictionary<string, string> mappings)
where T : new()
{
IList<PropertyInfo> properties = typeof (T).GetProperties().ToList();
IList<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((System.Data.DataRow) row, properties, mappings);
result.Add(item);
}
return result;
}
您可以使用簡單的Select()
語句。 但是,因為DataTable.Rows
是未實現IEnumerable<DataRow>
的DataRowCollection
,所以需要首先調用OfType<DataRow>()
:
public static IList<T> ToList<T>(this System.Data.DataTable table, Dictionary<string, string> mappings)
where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
return table.Rows.OfType<DataRow>().Select(row => CreateItemFromRow<T>(row, properties, mappings))
.ToList();
}
正如Harald在評論中建議的那樣,您可以使用Cast<DataRow>
代替OfType<DataRow>
。 區別在於OfType
檢查是否可以進行Cast
類型轉換,並且僅返回可Cast
元素, Cast
將Cast
所有元素(如果Cast
類型無效則拋出)。 由於我們知道此集合中的所有元素均為DataRow
類型,因此可以節省檢查時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.