Solved

Convert a IList into a datatable and filter the datatable

Posted on 2010-09-01
5
1,428 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
5 Comments
 
LVL 9

Expert Comment

by:puru1981
Comment Utility
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
Comment Utility

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 500 total points
Comment Utility

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
Comment Utility
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

744 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now