?
Solved

Convert a IList into a datatable and filter the datatable

Posted on 2010-09-01
5
Medium Priority
?
1,569 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 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

Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

770 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