सूची में कनवर्ट करने के लिए कैसे करें .Net।सूची <T> डेटाव्यू
10
A
उत्तर
18
मेरा सुझाव सूची को डेटाटेबल में परिवर्तित करना होगा, और उसके बाद अपना डेटा व्यू बनाने के लिए तालिका के डिफ़ॉल्ट दृश्य का उपयोग करना होगा।
सबसे पहले, आप डेटा तालिका का निर्माण करना होगा:
// <T> is the type of data in the list.
// If you have a List<int>, for example, then call this as follows:
// List<int> ListOfInt;
// DataTable ListTable = BuildDataTable<int>(ListOfInt);
public static DataTable BuildDataTable<T>(IList<T> lst)
{
//create DataTable Structure
DataTable tbl = CreateTable<T>();
Type entType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
//get the list item and add into the list
foreach (T item in lst)
{
DataRow row = tbl.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
tbl.Rows.Add(row);
}
return tbl;
}
private static DataTable CreateTable<T>()
{
//T –> ClassName
Type entType = typeof(T);
//set the datatable name as class name
DataTable tbl = new DataTable(entType.Name);
//get the property list
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
foreach (PropertyDescriptor prop in properties)
{
//add property as column
tbl.Columns.Add(prop.Name, prop.PropertyType);
}
return tbl;
}
इसके बाद, DataTable के डिफ़ॉल्ट दृश्य प्राप्त:
DataView NewView = MyDataTable.DefaultView;
एक पूरा उदाहरण के रूप में निम्नानुसार होगा:
List<int> ListOfInt = new List<int>();
// populate list
DataTable ListAsDataTable = BuildDataTable<int>(ListOfInt);
DataView ListAsDataView = ListAsDataTable.DefaultView;
+1
एक मामूली सुधार CreateTable भी स्थिर होना चाहिए। – user3141326
एक स्वीकार्य उत्तर की तुलना में अधिक ऑब्जेक्ट उन्मुख तरीके इस प्रश्न के उत्तर के समान विधि का उपयोग करना होगा। [क्वेरी अभिव्यक्तियों का उपयोग करके सूची को सूचीबद्ध करें] (http://stackoverflow.com/questions/695906/sort-a-listt-using-query-expressions) यह माना जा रहा है कि एकमात्र कारण है कि आप एक सूची चाहते हैं सॉर्टिंग कार्यक्षमता के लिए एक डाटाव्यू है। –
Amicable