-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathExtensions.cs
More file actions
51 lines (46 loc) · 1.12 KB
/
Extensions.cs
File metadata and controls
51 lines (46 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
namespace SoftwarePatterns.Core
{
public static class Extensions
{
public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
foreach (var c in collection)
{
action(c);
}
}
public static void ForEach<T>(this IEnumerable<T> collection, Action<T, int> action)
{
var i = 0;
foreach (var c in collection)
{
action(c, i++);
}
}
public static DataTable ToDataTable<T>(this IEnumerable<T> data)
{
var properties = TypeDescriptor.GetProperties(typeof(T));
var table = new DataTable();
foreach (var prop in properties.Cast<PropertyDescriptor>())
{
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (var item in data)
{
var row = table.NewRow();
foreach (var prop in properties.Cast<PropertyDescriptor>())
{
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(row);
}
return table;
}
}
}