如何在Linq join语句中添加默认null值 [英] How do I add default null values in a Linq join statement

查看:101
本文介绍了如何在Linq join语句中添加默认null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个IEnumerables.一个包含日期,另一个包含日期.

I have two 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 });

我正在尝试建立一个表,该表显示给定日期的Views.但是,数据存在一些差距.我如何编写一个将两个集合连接起来的linq查询,并在存在时返回Views编号,而在数据中没有匹配的对象时返回0?

I'm trying to build a table which shows the Views on a given day. 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?

我可以使用foreach语句以老式的方式执行此操作,但我想知道如何在Linq中执行此操作.

I can do this the old fashioned way with foreach statements but I'd like to know how to do it in Linq.

推荐答案

不确定我是否完全理解您的问题.如果您要生成具有至少一个视图的天数列表,则可以完成工作. /p>

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

零天无人居住

这篇关于如何在Linq join语句中添加默认null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆