Click here to Skip to main content
14,236,439 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi everyone,

I have one datatable in which there are many rows in this format

Id Itemset
1 beer,mango,diaper,wafers
2 bottle,laptop,mouse,keyboard

in this way..

Now i want to convert this datatable into list
i.e i will have unique itemset in my list. and they will be
as :
1. beer
2. mango
3. diaper
4. wafers
5. bottle
6. laptop
7. mouse
8. keyboard etc..

i want the list to be as according to the datatable items
i.e. list.add (new string(1,2,3,4)
list.add(new string(5,6,7,8)

please help me out how to achieve this.

Thanks & Regards,
Krunal Panchal
Posted
Comments
Prasad Khandekar 26-Mar-13 9:00am
   
Why not loop around the datatable and construct an arraylist all by yourself. You can use contains method to check for duplicate. You can then use the resulting arraylist. You can use String.split to break your Itemset.
joshrduncan2012 26-Mar-13 9:16am
   
Is this homework?
Rate this:
Please Sign up or sign in to vote.

Solution 1

This should do what you need. I've used the HashSet instead of a list as you mentioned you wanted the unique itemset, which would be a set not a list

// Example Table
DataTable tblItems = new DataTable("MyItems");
tblItems.Columns.Add(new DataColumn("Id", typeof(string)));
tblItems.Columns.Add(new DataColumn("Itemset", typeof(string)));

// Add the sample rows
tblItems.Rows.Add(new object[] { 1, "beer,mango, diaper, wafers"});
tblItems.Rows.Add(new object[] { 2, "bottle,laptop,mouse,keyboard" });

// As you want the unique items why not use a hashset instead of a list
HashSet<string> items = new HashSet<string>();

// Getting the row data into the set
foreach (DataRow dr in tblItems.Rows)
{
    var itemSet = dr["Itemset"].ToString().Split(',').ToList();
    itemSet.ForEach(i =>
    {
        if (!string.IsNullOrEmpty(i))
            items.Add(i.Trim());
    });
}

// Output the unique items
for (int i = 0; i < items.Count; i++ )
{
    Console.WriteLine(string.Format("{0} - {1}", i+1, items.ElementAt(i)));
}
   
v2
Comments
navin ks 27-Mar-13 6:32am
   
+5
Rate this:
Please Sign up or sign in to vote.

Solution 2

hi krunalpanchalN,
Try this code..

var fromDataTable = (from K in ((from DataRow c in dt.Rows select c).SelectMany(T => T["name"].ToString().Split(',').ToArray())) select new { Itemset = K });
            var test = fromDataTable.Select((fromDataTableNew, ee) => new { Id = ee + 1, Itemset = fromDataTableNew.Itemset });

            grdnew.DataSource = test;
            grdnew.DataBind();
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100