简体   繁体   English

如何在Linq连接语句中添加默认空值

[英]How do I add default null values in a Linq join statement

I have two IEnumerables . 我有两个IEnumerables One contains dates, the other contains data. 一个包含日期,另一个包含数据。

DateTime start = DateTime.Today.AddDays(-21);

var dates = Enumerable.Range(0, 21).Select(n => start.AddDays(n)).ToArray();

var data = MyClass.Data.Select(x => new { Date = x.Date, Views = x.Count });

I'm trying to build a table which shows the Views on a given day. 我正在尝试构建一个表格,显示给定日期的Views However, data contains some gaps. 但是,数据包含一些空白。 How do I write a linq query which joins the two sets, and returns the Views number when present or 0 when there is no matching object in data? 如何编写连接两个集合的linq查询,并在存在时返回Views编号,或者在数据中没有匹配对象时返回0?

I can do this the old fashioned way with foreach statements but I'd like to know how to do it in Linq. 我可以用foreach语句以老式的方式做到这一点,但我想知道如何在Linq中做到这一点。

This should work: 这应该工作:

var data = from day in Enumerable.Range(0, 21).Select(n => start.AddDays(n))
           join d in MyClass.Data.Select(x => new { Date = x.Date, Views = x.Count })
           on day equals d.Date into gj
           from dd in gj.DefaultIfEmpty()
           select new { Date = day, Views = dd == null ? 0 : dd.Views };

This returns the views-number when there is one at the given day and 0 otherwise. 如果在给定的日期有一个,则返回views-number,否则返回0。

How to: Perform Left Outer Joins 如何:执行左外连接

Not sure i fully understood your question.If you want to generate a list of days which has at least one views,then this will get the job done. 我不确定我完全理解你的问题。如果你想生成一个至少有一个视图的日期列表,那么这将完成工作。

DateTime start = DateTime.Today.AddDays(-21);

//Sample view data
var viewsData = new[] {new {id = "id", date = new DateTime(2013, 4, 12), views = 25}};

var dates = Enumerable.Range(0, 21)
                        .Select(d => start.AddDays(d))
                        .Select(n => new
                                        {
                                         Day = n,
                                         views =viewsData.Any(x => x.date == n)
                                         ? viewsData.FirstOrDefault(v => v.date == n).views
                                         : 0
                         });   

Zero is populated for days having no views 零填充了几天没有视图

Have a look at this MSDN article: http://msdn.microsoft.com/en-us/library/vstudio/bb397895.aspx 看看这篇MSDN文章: http//msdn.microsoft.com/en-us/library/vstudio/bb397895.aspx

It explains how to do a left outer join which is what you need in this case. 它解释了如何在这种情况下进行左外连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM