选择两列的最佳实践

时间:2013-08-29 15:39:41

标签: entity-framework-4 linq-to-entities

我有一些如下的查询

var email= (from c in dataContext.tblC
            where (c.AA == aa)
            select c.email).ToList();
string emails = email.Aggregate((a, b) => a + "," + b);

现在我需要另一个列SecEmail,我不能只是(...选择c.email,c.SecEmail).ToList()。 我的任何建议都可以获得(email1,SecEmail1,email2,email3,SecEmail3,email4 ......)列表

1 个答案:

答案 0 :(得分:0)

如果你正在使用动态对象:

var email = (from c in dataContext.tblC
             where c.AA == aa
             select new {
               email = x.email,
               secemail = c.secEmail,
               // ...
             }).ToList(); // IList<dynamic> & IDE will know what properties
                          // you supplied in the `select new { }`

否则建立一个模型并填充它:

public class SelectModel
{
    public String email { get; set; }
    public String secemail { get; set; }
}

var email = (from c in dataContext.tblC
             where c.AA == aa
             select new SelectModel {
               email = x.email,
               secemail = c.secEmail,
               // ...
             }).ToList(); // IList<SelectModel>

如果您希望将返回的行设置为电子邮件to标题:

var email = String.Join(", ", (
              from c in dataContext.tblC
              where c.AA == aa
              select c.email
            ).AsEnumerable());

哪会:

+------------------+
| email            |
|------------------|
| foo@contoso.com  |
| bar@contoso.com  |
| baz@contoso.com  |
+------------------+

请转到:

foo@contoso.com, bar@contoso.com, baz@contoso.com

多列c​​oncat:

var email = (from c in dataContext.tblC
             where c.AA == AA
             select new { email = c.email, secEmail = c.secEmail }).AsEnumerable();
var to = String.Join(", ",
    email.Select(x => x.email)
        .Concat(email.Select(y => y.secEmail))
        // .Concat(eail.Select(y => x.thirdColumn))
        // ...
);