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

时间:2014-06-02 15:49:12

标签: c# linq

我有一个由以下人员定义的集合:

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

我知道这个想法可以执行,但我的语法错了吗?

1 个答案:

答案 0 :(得分:3)

试试这个:

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}

您尝试声明一个名为公司的本地变量,该变量应属于集合。 因此我们应该写如下:

var pairs = from item in items

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

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