[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Convert a IList into a datatable and filter the datatable

Posted on 2010-09-01
5
Medium Priority
?
1,637 Views
Last Modified: 2016-09-19
Hi,

I would like to be able to convert an IList into a datatable and then also filter the datatable. How can I do this?

(Would prefer an answer made in vb.net)

Peter
0
Comment
Question by:peternordberg
4 Comments
 
LVL 9

Expert Comment

by:puru1981
ID: 33575575
public static DataTable convertToTable(object[] objs)
        {
            Type t = objs.GetType();
            DataTable dt=new DataTable();
            Type elementType=null;
            foreach (object obj in objs)
            {
                elementType = obj.GetType();
                break;
            }
           
            if (!t.IsArray)
                throw new Exception("Can't convert this object to Table");
            else
            {
                MemberInfo[] fis = elementType.GetMembers(BindingFlags.Public | BindingFlags.Instance);
                foreach (MemberInfo fi in fis)
                {
                    if (fi.MemberType == MemberTypes.Property)
                    {
                        PropertyInfo pi = fi as PropertyInfo;
                        dt.Columns.Add(pi.Name, pi.PropertyType);
                    }
                    else if (fi.MemberType == MemberTypes.Field)
                    {
                        FieldInfo pi = fi as FieldInfo;
                        dt.Columns.Add(pi.Name, pi.FieldType);
                    }
                }
                foreach (object obj in objs)
                {
                    int i = 0;
                    object[] fieldValues = new object[dt.Columns.Count];
                    foreach (DataColumn c in dt.Columns)
                    {
                        MemberInfo mi = elementType.GetMember(c.ColumnName)[0];
                        if (mi.MemberType == MemberTypes.Property)
                        {
                            PropertyInfo pi = mi as PropertyInfo;
                            fieldValues[i] = pi.GetValue(obj, null);
                        }
                        i++;
                    }
                    dt.Rows.Add(fieldValues);

                }
            }
            return dt;
        }


0
 
LVL 16

Expert Comment

by:kris_per
ID: 33576947

See if the following would work for your data:

1. Convert the List into xml using XmlSerializer
2. Then load the xml in DataSet
Now DataSet.Tables property will have the data in a DataTable object
3. Use DataView to filter the data from DataTable.


Imports System.Collections.Generic
Imports System.Data
Imports System.IO
Imports System.Xml.Serialization

Namespace WindowsFormsApplication4
	Public Class MyObject
		Public Name As String
		Public Id As Integer
	End Class

	Public Class Sample
		Public Sub SampleMethod()
			Dim list As New List(Of MyObject)()
			list.Add(New MyObject() With { _
				Key .Name = "one", _
				Key .Id = 1 _
			})
			list.Add(New MyObject() With { _
				Key .Name = "two", _
				Key .Id = 2 _
			})

			' serialize the list to xml
			Dim ser As New XmlSerializer(GetType(List(Of MyObject)))
			Dim stream As Stream = New FileStream("temp.xml", FileMode.Create)
			ser.Serialize(stream, list)
			stream.Dispose()

			' load the xml into a dataset
			Dim ds As New DataSet()
			ds.ReadXml("temp.xml")

			' get the datatable
			Dim dataTable As DataTable = ds.Tables(0)

			' filter it
			Dim dataView As New DataView(dataTable, "Name='one'", "Name", DataViewRowState.CurrentRows)

			' now dataView contains the filtered data
		End Sub
	End Class
End Namespace

Open in new window

0
 
LVL 9

Accepted Solution

by:
abhinayp86 earned 2000 total points
ID: 33580305

private DataTable ListToDataTable<T>(List<T> list)
    {
        DataTable dt = new DataTable();

        foreach (PropertyInfo info in typeof(T).GetProperties())
        {
            dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
        }
        foreach (T t in list)
        {
            DataRow row = dt.NewRow();
            foreach (PropertyInfo info in typeof(T).GetProperties())
            {
                row[info.Name] = info.GetValue(t, null);
            }
            dt.Rows.Add(row);
        }
        return dt;
    }

Open in new window

0
 

Expert Comment

by:Anindita De
ID: 41804792
Hi,
I am trying to take a gridview in ViewState, for that I need to store an IList value(which is returning database value) into DataTable so trying to convert the IList into Datatable and implemented the above code but this is not working for Ilist, Here is my code as follows:
void bindGrid(int iFacilityId)
        {
            BLRoom objRoomBL = new BLRoom(System.Configuration.ConfigurationManager.ConnectionStrings["dbGuestHouseConnectionString"].ConnectionString);

            IList lst_BORoom = null;
            string strStatus = "Success";

            lst_BORoom = objRoomBL.GetAllRoombyFacilityId(iFacilityId, out strStatus);
            if (strStatus == "Success")
            {
                if (lst_BORoom.Count > 0)
                {
                    //DataTable dtCurrentTable = (DataTable)ViewState["lst_BORoom"];  
                    //DataTable dt = ConvertListToDataTable(Convert.ToString(lst_BORoom));
                    //ViewState["ExistingTable"] = lst_BORoom.;
                    DataTable dtoldRooms = new DataTable();
                    dtoldRooms = ConvertListToDataTable(lst_BORoom);
                   
                    trGrid.Visible = true;
                    trSection.Visible = true;
                    GridRoom.DataSource = lst_BORoom;
                    GridRoom.DataBind();
                }
                else
                {
                    trGrid.Visible = false;
                    trSection.Visible = false;
                    DisplayMessage("No rooms configured for this facility.", "red", true);
                }
            }
            else
            {
                trGrid.Visible = false;
                trSection.Visible = false;
                DisplayMessage("Unable to Load: Error in loading data.", "red", true);
            }

           

        }
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question