srikanth
srikanth

Reputation: 159

Get the row id that have same first name and last name

id    fname     lname     role
1     mark      anthony   lead
2     jeff      juarez    manager
3     matthew   gonzales  lead
4     mark      anthony   lead

i have the above table.

now i need to get the id's of all the rows that have same first name and last name.

i tried tbe below solution it is not working

foreach (DataRow row1 in dataTable.Rows)
{
    foreach (DataRow row2 in dataTable.Rows)
    {
           var array1 = row1.ItemArray;
           var array2 = row2.ItemArray;

           if (array1[1] == array2[1])
           {
               Console.WriteLine("Equal");
           }
           else
           {
               Console.WriteLine("Not Equal");
           }
    }
}

Upvotes: 0

Views: 562

Answers (3)

Hogan
Hogan

Reputation: 70529

You have to look at both first name and last name, like this:

foreach (DataRow row1 in dataTable.Rows)
    foreach (DataRow row2 in dataTable.Rows)
    {
        var array1 = row1.ItemArray;
        var array2 = row2.ItemArray;

        if ((array1[1] == array2[1]) && (array1[2] == array2[2]))
        {
            Console.WriteLine("ID#" + array1[0].ToString() + " is equal to ID#" + array2[0].ToString());
        }
        else
        {
            Console.WriteLine("Not equal");
        }
    }

UPDATE - To remove the finding self issue change the if statement like this

if ((array1[0] != array2[0]) && (array1[1] == array2[1]) && (array1[2] == array2[2]))

Upvotes: 3

Cubicle.Jockey
Cubicle.Jockey

Reputation: 3328

You can also try something like this:

var result = from dt in dataTable.AsEnumerable()
             group dt by new { FirstName = dt.Field<string>("FirstName"), LastName = dt.Field<string>("LastName")} into g
             where g.Count() > 1
             select dt.id;

Upvotes: 0

MattW
MattW

Reputation: 13212

I am assuming that you mean, get All ID's where the First Name = Last Name (Like "Mark Mark").

DataRow[] searchResults = dataTable.Select("fname = lname");

or, to loop

foreach (DataRow dr in dataTable.Select("fname = lname"))
{
     //Do something cool.
}

Upvotes: 0

Related Questions