在Linq列表中包含多个值

本文关键字:包含多 Linq 列表 | 更新日期: 2023-09-27 18:07:16

我有一个使用LINQ填充的选择列表,使用以下代码:

public List<string> getCustomerNames()
{
     var Customers = (from c in _context.OCRDs
     where c.CardType == "c"
     select c.CardCode
     ).ToList();
     return Customers;
}

我试图创建一个多列列表,以便'CardCode'可以是值和'CardName'可以作为列表中的描述。

例如:

C001 Name1

C002 Name2

在Linq列表中包含多个值

创建新的结果类并在该类中查询值:

class Item
{
    public string CardCode {get;set;}
    public string CardName {get;set;}
}
public List<Item> getCustomerNames()
{
     var Customers = (from c in _context.OCRDs
                      where c.CardType == "c"
                      select new Item { CardCode = c.CardCode, CardName = c.CardName }
                      ).ToList();
     return Customers;
}

您可以使用Dictionary代替List:

public Dictionary<string, string> GetCustomerNames()
{ 
     var Customers = (from c in _context.OCRDs
                      where c.CardType == "c"
                      select c)
                      .ToDictionary(c => c.CardCode, c => c.CardName);
     return Customers;
}