[CSHARP] Function convert DataTable to List và ngược lại trong lập trình csharp

Chào mọi người, bài viết này mình sẽ hướng dẫn mọi người về việc vòng lặp truyền dữ liệu qua lại giữa DATABASE.

Trong lập trình csharp, tùy trường hợp ta cần sử dụng List hoặc datatable để xử lý. Thì với 2 hàm bên dưới sẽ giúp cho các bạn dễ dàng chuyển đổi.

Chúng ta bắt đầu nhé.

1. Function chuyển đổi List to Datatable C#

public static DataTable ListToDataTable(this IList data)
	{
		DataTable dataTable = new DataTable(typeof(T).Name);
		PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
		foreach (PropertyInfo prop in props)
		{
			dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
		}
		foreach (T item in data)
		{
			var values = new object[props.Length];
			for (int i = 0; i < props.Length; i++)
			{
				values[i] = props[i].GetValue(item, null);
			}
			dataTable.Rows.Add(values);
		}
		return dataTable;
	}

2. Function chuyển đổi từ Datatable to List C#

public static List DataTableToList(this DataTable table) where T : class, new()
	{
		try
		{
			List list = new List();
 
			foreach (var row in table.AsEnumerable())
			{
				T obj = new T();
 
				foreach (var prop in obj.GetType().GetProperties())
				{
					try
					{
						PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
						propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
					}
					catch
					{
						continue;
					}
				}
 
				list.Add(obj);
			}
 
			return list;
		}
		catch
		{
			return null;
		}
	}	

Chúc mọi người thành công với hướng dẫn trên, nếu mọi người gặp lỗi gì có thể liên hệ mình để được hỗ trợ nhé.