如何在linq中从集合中选择两个集合

本文关键字:集合 两个 选择 linq | 更新日期: 2023-09-27 18:06:11

我有一个集合,定义为:

public class CompanyModel
{
    public int compnSN { get; set; }
    public string compnName { get; set; }
    public string compnAddress { get; set; }
}

我如何同时得到两个集合compnNamecompnAddress,以便我可以在foreach循环中逐个使用这对值?我试着:

var pairs = from companies 
            select new {name = companies.compnName, addr = companies.compnAddress}
foreach (var item in pairs)
{
    //do some things with item.name;
    //do some things with item.addr;
}

我知道这个想法可以执行,但我的语法错误的地方?

如何在linq中从集合中选择两个集合

试试这个:

var result = companies.Select(x => new 
                                   { 
                                       Name = x.compnName, 
                                       Address = x.compnAddress 
                                   });

或者这个

var result = from company in companies
             select new 
             {
                  Name = x.compnName, 
                  Address = x.compnAddress 
             };

那么正如你已经指出的:

foreach(var company in result)
{
    // access the name like company.Name and do what you want.
    // access the address like company.Address and do what you want.
}

你发布的代码有一些语法错误。因此,尽管您的逻辑是正确的,这段代码将不会被编译。

具体来说,在下面一段代码中:

var pairs = from companies 
            select new {name = companies.compnName, addr = companies.compnAddress}

尝试声明一个名为companies的局部变量,它应该属于集合。因此,我们应该这样写:

var pairs = from item in items

现在item是一个局部变量,它引用了集合中称为items的随机元素。然后,正如你已经写过的,你将在select子句中声明一个匿名类型:

var pairs = from item in items
            select new
            {
                PropertyA = item.PropertyA
                PropertyB = item.PropertyB
            };