简体   繁体   中英

Linq to query matching column from a table and populate in another table

I have a table as below:

Id First Name Last Name
1 John Murray
2 Smith Murray
3 Natasha Murray
4 Steve Kay
5 Bill Kay

Now, If I query for a name example John , it should produce the results with the matching records with same lastname and put into another table as below:

Id Name Matching name
1 John Smith
2 John Natasha

How can i achieve this using Linq?

Lets define the class for data

class Table
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

this is something that should be part of your question. Now fill in the data

Table[] table = new Table[]
{
    new Table{ Id = 1, FirstName = "John", LastName = "Murray" },
    new Table{ Id = 2, FirstName = "Smith", LastName = "Murray" },
    new Table{ Id = 3, FirstName = "Natasha", LastName = "Murray" },
    new Table{ Id = 4, FirstName = "Steve", LastName = "Kay" },
    new Table{ Id = 5, FirstName = "Bill", LastName = "Kay" }
};

and that is also something that should be part of your question. If you omit that you greatly reduce chance of getting an aswer. Now just join the table with itself on the last name.

var query = from t1 in table
            from t2 in table
            where t1.LastName == t2.LastName && t1.Id != t2.Id
            select new { t2.Id, Name = t1.FirstName, MatchingName = t2.FirstName };

foreach (var row in query.Where(t => t.Name == "John"))
{
    Console.WriteLine(row);
}

and voilà

 { Id = 2, Name = John, MatchingName = Smith }
 { Id = 3, Name = John, MatchingName = Natasha }

The only thing that is different is the Id, from the data provided I have no idea how John or Natasha could be related to Id number 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM