【问题标题】:Linq to query matching column from a table and populate in another tableLinq 从表中查询匹配列并填充到另一个表中
【发布时间】:2021-05-13 07:45:07
【问题描述】:

我有一张如下表:

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

现在,如果我查询一个姓名示例 John,它应该产生具有相同姓氏的匹配记录的结果,并放入另一个表中,如下所示:

Id Name Matching name
1 John Smith
2 John Natasha

我如何使用 Linq 实现这一点?

【问题讨论】:

  • 是 SQL Server 表吗?
  • 是的。我希望在 linq 中查询它以在我的课堂上使用它
  • 看起来像简单的自我加入。你尝试了什么?
  • 我为此编写了一个 sql 查询...但我想将其转换为 linq .. select * from table d inner join ( select lastName from table where lastName = 'Murray' group by lastName has count ( distinct firstName) > 1) dup on dup.lastName = d.lastName ;

标签: c# linq


【解决方案1】:

让我们定义数据类

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

这应该是您问题的一部分。现在填写数据

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" }
};

这也是您问题的一部分。如果你忽略了,你会大大降低获得答案的机会。现在只需在姓氏上加入表格。

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);
}

然后瞧

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

唯一不同的是 ID,从提供的数据来看,我不知道 John 或 Natasha 如何与 ID 2 相关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多