LINQで結合


Joinを使って2つのListを結合

Company.cs
class Company
{
    public string Name { get; set; }
    public string Market { get; set; }

    public Company(string name, string market)
    {
        Name = name;
        Market = market;
    }
}
Stock.cs
class Stock
{
    public string Name { get; set; }
    public int Price { get; set; }

    public Stock(string name, int price)
    {
        Name = name;
        Price = price;
    }
}
List<Company> companys = new List<Company>();

companys.Add(new Company("あいうえ株式会社", "東証1部"));
companys.Add(new Company("株式会社かきくけ", "東証2部"));

List<Stock> stocks = new List<Stock>();

stocks.Add(new Stock("あいうえ株式会社", 1055));
stocks.Add(new Stock("株式会社かきくけ", 7832));

foreach(var item in companys.Join(stocks, c => c.Name, c => c.Name, (p1, p2) => new { p1.Name, p1.Market, p2.Price}))
{
    Debug.WriteLine($"{item.Name} {item.Market} {item.Price} 円");
}