简体   繁体   English

Linq 从表中查询匹配列并填充到另一个表中

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

I have a table as below:我有一个如下表:

Id ID First Name Last Name
1 1 John约翰 Murray默里
2 2 Smith史密斯 Murray默里
3 3 Natasha娜塔莎 Murray默里
4 4 Steve史蒂夫 Kay
5 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:现在,如果我查询名称示例John ,它应该产生具有相同姓氏的匹配记录的结果,并放入另一个表中,如下所示:

Id ID Name姓名 Matching name匹配名称
1 1 John约翰 Smith史密斯
2 2 John约翰 Natasha娜塔莎

How can i achieve this using Linq?我如何使用 Linq 实现这一目标?

Lets define the class for data让我们为数据定义 class

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.唯一不同的是 ID,从提供的数据来看,我不知道 John 或 Natasha 如何与 ID 2 相关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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