简体   繁体   中英

Convert foreach to LINQ statement

What is the linq expresson for that? I do not know how to change the foreach statement into a linq expression.

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

You can use a simple Select() statement. But because DataTable.Rows is a DataRowCollection that does not implement an IEnumerable<DataRow> you need to call OfType<DataRow>() first:

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

As Harald suggests in the comments, you may use Cast<DataRow> instead of OfType<DataRow> . The difference is that OfType checks if the cast is possible and only returns castable elements, Cast will cast all elements (and throw if the cast is invalid). Since we know that all elements in this collection are of type DataRow we can save the time for the check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM