首页 \ 问答 \ C#Linq如何枚举两个日期之间的时间段以获取图表的数据(C# Linq How to enumerate over time periods between two dates to get data for a graph)

C#Linq如何枚举两个日期之间的时间段以获取图表的数据(C# Linq How to enumerate over time periods between two dates to get data for a graph)

我有一个在某些日期发生的事件表,知道我想格式化数据,以便能够绘制事件的线图随着时间的推移。 数据的标签是x轴上的值,数据是y轴上的值。

数据应该在两个日期之间,在这个例子中它是from和to,然后它必须是几天的时间间隔

这是我的第一次尝试。

var graphData = bookings.Where(x => x.DateCreated > from && x.DateCreated < to)
                        .GroupBy(x => new { x.DateCreated.Year, x.DateCreated.Month, x.DateCreated.Day })
                        .OrderBy(x => x.Key.Year).ThenBy(x => x.Key.Month).ThenBy(x => x.Key.Day)
                        .Select(x => new GraphData
                        {
                            Label = x.Key.Day + "/" + x.Key.Month + "/" + x.Key.Year,
                            Data = x.Count()
                        }).ToList();

这为我提供了正确的数据图, 但仅限于创建任何事件的日期。

我希望在我的图表中包含未发生任何事件的日期的数据,以便我可以在同一图表上比较不同类型的事件。

我想出了这个解决方案

var dateRanges = Enumerable.Range(0, 1 + to.Value
                           .Subtract(from.Value).Days)
                           .Select(offset => from.Value.AddDays(offset)).ToList();
var graphData = dateRanges.Select(day => new GraphData()
                {
                   Label = day.ToString("D"),
                   Data = bookings.Count(x => x.DateCreated.Date == day.Date)
                }).ToList();

这似乎是非常低效的。

是否有任何方法可以使用linq查询执行此操作,以便我不必对每个日期进行计数?


I have a table of events that occur on certain dates, know i want to format the data to be able to draw a line graph of events over time. The data has a label which is the value on the x axis and data which is the value on the y axis.

The data should be between two dates, in this example its from and to and then it must be in time intervals of days

This was my first attempt.

var graphData = bookings.Where(x => x.DateCreated > from && x.DateCreated < to)
                        .GroupBy(x => new { x.DateCreated.Year, x.DateCreated.Month, x.DateCreated.Day })
                        .OrderBy(x => x.Key.Year).ThenBy(x => x.Key.Month).ThenBy(x => x.Key.Day)
                        .Select(x => new GraphData
                        {
                            Label = x.Key.Day + "/" + x.Key.Month + "/" + x.Key.Year,
                            Data = x.Count()
                        }).ToList();

This give the correct data for me to graph but only for the days which there where any events created.

I want to have the data for the days where nothing happened included in my graph so i can compare different kinds of events on the same graph.

I came up with this solution

var dateRanges = Enumerable.Range(0, 1 + to.Value
                           .Subtract(from.Value).Days)
                           .Select(offset => from.Value.AddDays(offset)).ToList();
var graphData = dateRanges.Select(day => new GraphData()
                {
                   Label = day.ToString("D"),
                   Data = bookings.Count(x => x.DateCreated.Date == day.Date)
                }).ToList();

It seems to be very inefficient.

Is there any way to do this with a linq query so that i don't have to do a count on each date?


原文:https://stackoverflow.com/questions/42276647
更新时间:2021-07-14 15:07

最满意答案

我想这会对你有所帮助

<img class="media-object image-size" data-bind="attr:{src: headlineImage}" style="width:100%; height:100%"/>


I think this will help you

<img class="media-object image-size" data-bind="attr:{src: headlineImage}" style="width:100%; height:100%"/>

相关问答

更多
  • 所以,为了没有在评论中的所有内容我发布答案。 屏幕/视口宽度为380px及以下的“问题”存在几个问题。 在您的外部
    使用类slider-wrapper3 (它是将iPhone作为背景图像保存的那个),您应该在CSS中使用以下内容: .slider-wrapper3 { background-size: contain; /* you use cover */ background-repeat: no-repeat; /* keep the rest of your actual ...
  • 填充使它浮动 ,它符合你设置的规则(边距为45px),如果你想要它在左上角: 有关示例,请参见http://jsfiddle.net/9KJA7/ /* Ignore */ .logoHeader {background-color: red} img {height: 50px; width: 50px; background-color: green} /* Your code */ .logoHeader {padding:45px 20px 0px 20px; position: relative ...
  • 它应该是onclick='slideit()' 您Uncaught ReferenceError: images1 is not defined的原因是因为它正在尝试eval('images1.src')和(我不认为)代码中有如window.images1 , window.images2或window.images3 。 您可能想要的是定义一个src array ,然后获取srcsArray[step]并将其用作document.images.slide新src 。 正如@ patrick-evans所说 ...
  • 找到了解决方案。 它非常粗糙,不够优雅。 txtDaMessage.Text = txtDaMessage.Text.Replace("< ;", "<"); txtDaMessage.Text = txtDaMessage.Text.Replace("> ;", ">"); 逻辑是因为AjaxControlToolKit想要自动将我'<' html图像标记的'<'和'>'转换为"< ;" 和"> ;" 我将分别使用replace方法强制它们恢复原始形式。 Found the soluti ...
  • 我想这会对你有所帮助 I think this will help you
  • image_tag是根据ActionView :: Helpers :: TagHelper.tag实现的 ,它采用可选的第三个参数来表示是否关闭标记(对于XHTML兼容性)。 默认情况下它已关闭,但有些东西会将您设置为true。 不知道在哪里。 你应该可以说 tag(:img, { :src => "test.jpg" }, false) 迫使它。 注意使用:img而不是"img" 。 :img是一个符号 ,基本上是一个只创建一次的字符串。 另一方面,每次调用tag时都会创建一个新字符串"img" , ...
  • 如何创建一个元素并将字符串设置为内部HTML,然后查找图像并将其删除? 例如 var container = document.createElement('div'); container.innerHTML = text; var img = container.querySelector('img[src="' + image + '"]'); container.removeChild(img); var newtext = container.innerHTML; 的jsfiddle How ...
  • 假设你有这样一个元素: 你可以这样做: $("#mycode").append($("
    ").append($('img').clone()).html()); 或者,如果您希望半编码显示,如下所示: var html = $("
    ").append($('img').clone()).html(); $("#mycode").append(html.replace('<','<').replace('>','>')) ...
  • 我猜这个例子会帮助你http://jsfiddle.net/handtrix/yvq5y/ 但在你的情况下,而不是: var imageUrl = $(this).find('[name=url]').val(); 添加以下行 var imageUrl = $(this).find('img').attr('src'); 这样的事情应该为你做。 PS:我没有自己在网上找到它的小提琴 UPDATE 这是一个修复CORS问题的版本 https://jsfiddle.net/9hjpdect/9/ I guess ...
  • 如果Graphics是项目目录中的文件夹,那么给出@Url.Content()相对路径,它将自己处理它。 以这种方式给网址: If Graphics is the folder in your project directory then give relative path to @Url.Content() and it will handle it itself. give url this ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)