如何使用linq语句查询?

时间:2012-03-26 11:30:10

标签: c# linq

我有两个对象

List<Report> 
List<Newsletter>

我需要某些属性,比如

Id
Date
Status
text

来自两个名单。有没有办法合并这些列表并使用linq语句查询它以将特定属性作为单独的列表返回? 请帮忙。

对象的结构如下:

Report
{
    int id,
    datetime reportDate, 
    enum Status,
    string text
};

Newsletter
{
    int id, 
    datetime newsletterDate,
    string Status,
    string text
};

4 个答案:

答案 0 :(得分:6)

var items = 
      reportList.Select(x =>  new { x.Id, x.Date, x.Status, x.text })
      .Concat(
        newsList.Select(x =>  new { x.Id, x.Date, x.Status, x.text }) );

更新,以平衡状态属性:

var items = 
      reportList.Select(x =>  new { x.Id, x.Date, Status = x.Status.ToString(), x.text })
      .Concat(
        newsList.Select(x =>  new { x.Id, x.Date, Status, x.text }) );

答案 1 :(得分:4)

假设列表中包含公共列并在它们之间应用连接..

您可以加入,然后获取以下数据

var data = form a in lista
join b in listb on
a.id equals b.id
select new {id=a.id, Date= b.Date, Status=a.Sttus, text=b.Text};

以下是两个表用户和userclient之间的连接图像

查看完整文章:Case 4 - JOINING TWO TABLE

enter image description here

答案 2 :(得分:4)

var reps = reposts.Select(r => new { Id = r.Id, Date = r.Date, Status = r.Status, Text = r.Text});
var news = newsletters.Select(n => new { Id = r.Id, Date = r.Date, Status = r.Status, Text = r.Text});
var result = reps.Union(news);

答案 3 :(得分:3)

 var query = reports.Select(x => new { x.Id, x.Date, Status = Enum.GetName(typeof(Status), x.Status), x.Text })
.Union(news.Select(x => new { x.Id, x.Date, x.Status, x.Text }));