簡體   English   中英

Linq 從表中查詢匹配列並填充到另一個表中

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

我有一個如下表:

ID
1 約翰 默里
2 史密斯 默里
3 娜塔莎 默里
4 史蒂夫
5 賬單

現在,如果我查詢名稱示例John ,它應該產生具有相同姓氏的匹配記錄的結果,並放入另一個表中,如下所示:

ID 姓名 匹配名稱
1 約翰 史密斯
2 約翰 娜塔莎

我如何使用 Linq 實現這一目標?

讓我們為數據定義 class

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 相關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM