Solved

Filtering common fields from datatables without loops

Posted on 2010-09-07
13
668 Views
Last Modified: 2012-05-10
Hi,
I have a dataset with 2 datatables in it. One has the list of Employees from Department1 and the other has the list of Employees from Department2. I need the list of employees (as a datatable) who belong to both Department1 and Department2. How can this be done without loops?
0
Comment
Question by:rajasoorya_kc
[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
  • 4
  • 3
  • 3
  • +2
13 Comments
 
LVL 22

Expert Comment

by:Om Prakash
ID: 33624329
DataTable Relational Operators in C# - UNION Method
http://weblogs.sqlteam.com/davidm/archive/2004/01/15/724.aspx

but this loops through both table and gives one datatable.
0
 

Author Comment

by:rajasoorya_kc
ID: 33624456
Thanks Om Prakash
But I am looking for a solution with no loops involved. Is there a way?
0
 
LVL 53

Accepted Solution

by:
Dhaest earned 125 total points
ID: 33624489
Below you can find a small example, where I created 2 datatables and give the result back through a linq-query
        private void linqJoin()
        {
            // department1 datatable
            DataTable department1 = new DataTable("Department1");
            department1.Columns.Add(new DataColumn("EmployeeName"));
            DataRow datarow = department1.NewRow();
            datarow[0] = "alfa";
            department1.Rows.Add(datarow);
            datarow = department1.NewRow();
            datarow[0] = "beta";
            department1.Rows.Add(datarow);
            datarow = department1.NewRow();
            datarow[0] = "charlie";
            department1.Rows.Add(datarow);

            // department1 datatable
            DataTable department2 = new DataTable("Department2");
            department2.Columns.Add(new DataColumn("EmployeeName"));
            datarow = department2.NewRow();
            datarow[0] = "alfa";
            department2.Rows.Add(datarow);
            datarow = department2.NewRow();
            datarow[0] = "beta";
            department2.Rows.Add(datarow);
            datarow = department2.NewRow();

            var dataRows = from  dataRows1 in department1.AsEnumerable() 
                            join  dataRows2 in department2.AsEnumerable() 
                            on dataRows1.Field<string>("EmployeeName") equals dataRows2.Field<string>("EmployeeName") 
                            select dataRows1;

Open in new window

0
Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

 
LVL 7

Expert Comment

by:illusio
ID: 33625013

Hi,
If the intent on avoiding loops is to increase performance, you can use a simple system with three passes through the datatables (2 sorting passes and one iteration).

- Sort both datatables on the employee id or name (whatever is appropriate).
- Then write a single loop with two indexes (pseudocode):
while (table1Index < table1.Count && table2Index < table2.Count)
{
        if (table1[table1Index].Employee == table2[table2Index].Employee) {
              tableResult.Add(table1[table1Index])
              table1Index++; table2Index++;
        } else {
               if (table1[table1Index].Employee < table2[table2Index].Employee)
                       table1Index++;
                else
                       table2index++;
       }
}

Kind regards,
Peter
0
 
LVL 8

Assisted Solution

by:Gururaj Badam
Gururaj Badam earned 125 total points
ID: 33625019

DataTable dt1 = CreateEmployeeTable();
            DataTable dt2 = CreateEmployeeTable();

            DataSet ds = new DataSet();
            ds.Tables.Add(dt1);
            ds.Tables.Add(dt2);

            ds.Relations.Add(new DataRelation("Employees", dt1.Columns["EmpId"], dt2.Columns["EmpId"]));

            var empIds = from emp in ds.Tables[0].Rows.Cast<DataRow>()
                                  where emp.GetChildRows().Count<DataRow>() > 0
                                  select emp["EmpId"];

private DataTable CreateEmployeeTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("EmpId");
            table.Columns.Add("EmpName");

            return table;
        }

Open in new window

0
 

Author Comment

by:rajasoorya_kc
ID: 33625145
Thanks for the tip Dhaest
You suggestion helped. Here is the modified code to convert the selected rows to a datatable
IEnumerable<DataRow> enumerableDataRowCollection = from subSiteRows in subSites.AsEnumerable()
                               join groupNameRows in dataGroupNames.AsEnumerable()
                                   on subSiteRows.Field<string>("Title") equals groupNameRows.Field<string>("GroupName")
                               select subSiteRows;
                dataSource = enumerableDataRowCollection.CopyToDataTable<DataRow>();

Open in new window

0
 
LVL 53

Expert Comment

by:Dhaest
ID: 33625222
>> Thanks for the tip Dhaest

Why did'nt you accept my solution than ?
0
 

Author Comment

by:rajasoorya_kc
ID: 33625257
Oops... i clicked the wrong one
NOM to Novice. Novice's suggestion was right too.
Is there a way to accept two solutions?
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33625270
Ask admin!
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 33625276
just click the button Request Attention  (first post), and then tell in the comments that you want to split the points
0
 
LVL 8

Expert Comment

by:Gururaj Badam
ID: 33625285
Before you do that clearly judge which one you wish to accept as solution.

It's not just for points but later ppl may come to this to follow what has been accepted as solution and implement the same in their problem.

I don't mind if awarded points will be revoked but as far as the problem has been answered correctly and accurately.
0
 

Author Closing Comment

by:rajasoorya_kc
ID: 33627465
Thanks for the suggestions
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

740 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