草庐IT

C#在几个月内有所不同?

coder 2023-10-17 原文

我正在用 C# 开发一个项目。我有一个名为 ExamResult 的模型其中有一个名为 Date 的字段,定义为 String .

然后我定义如下

        var executionQuery = (from x in db.ExamResult
                     where x.Student.Equals(iStudent)
                     orderby x.Date
                     select *);

日期获取格式为 <YEAR>-<MONTH> 的值 像这样

2014-01
2013-04
2013-09

我想做的是创建一个表,该表获取所有返回日期的最小值,并创建一个表,该表与该最小日期的月数有差异。

例子:

当我们得到如上的结果时,我想得到下表(如果我们得到最小值是 2013-04)

9
0
5

我尝试执行以下操作,但我得到了 System.NotSupported异常

var dates = executionQuery.Select(x => int.Parse(x.Date.Substring(0,
4)) * 12 + int.Parse(x.Date.Substring(5, 2)) -
int.Parse(minDate.Substring(0, 4)) * 12 -
int.Parse(minDate.Substring(5, 2)));

你知道我该怎么做吗?

最佳答案

我会用一个小的 Func<TIn, TOut>委托(delegate)将您的字符串日期转换为 DateTimes,然后它们可以正确排序。

首先,一个将日期字符串转换为 DateTime 的简单方法对象:

// Split the string and instantiate new DateTime object to sort by later
Func<string, DateTime> getDate = s => {
    int[] dateParts = s
        .Split(new char[] {'-'})
        .Select(dp => int.Parse(dp))
        .ToArray();

    // Let's use the new DateTime(int year, int month, int day) constructor overload
    // dateParts[0] is the year and dateParts[1] is the month;
    // the magic number 1 below  is just a day to give to the DateTime constructor
    return new DateTime(dateParts[0], dateParts[1], 1); 
};

您的代码可能看起来像这样;我无法测试你的代码,所以这将取决于你如何让它工作:

注意我把你的Linq分开了查询并在 C# 中进行排序;这样您就可以随心所欲地从数据库中获取东西,然后订购这些元素。我希望这行得通;否则,你必须调用我 getDate Func两次 - 一次 orderby , 和一次 select ;我不喜欢那个选项。

// The select now builds an anonymous object; You can also create a new class, ExamResultWithDate,
// for example, that has all fields of ExamResult plus a DateTime field; OR you can just add that 
// property to the partial class generated by EF or Linq-to-Sql or whatever right on the ExamResult 
// entity.

var executionQuery = (from x in db.ExamResult
                     where x.Student.Equals(iStudent)
                     select new { Entity = x, ActualDate = getDate(x.Date) }); // note select * as in your OP doesn't compile :)

var orderedQuery = executionQuery
    .OrderBy(eq => eq.ActualDate)
    .Select(er => er.Entity); // gets you just the entities in this case and discards the dates

要获得不同的日期,只需对您的最短日期做一些简单的计算: 同样,这是您程序的伪代码;

// Let's get the minimum date and difference in months;
DateTime minDate = executionQuery
    .ToList()
    .Select(o => o.ActualDate)
    .Min();

// I am just using the dates here but you can easily use your entire entity or whatever you need
Dictionary<DateTime, int> datesWithMonthDifference = executionQuery
    .ToDictionary(
        eq => eq.ActualDate
        eq => ((eq.Year - minDate.Year) * 12) + eq.Month - minDate.Month // this formula calculates month difference as an integer 
    );

这是一个可以满足您需要的工作程序: 请注意,这只是一个示例,需要适合您的项目。

using System;
using System.Collections.Generic;
using System.Linq;

namespace DateTimeFromString
{
    class Program
    {

        static void Main(string[] args)
        {

            List<string> dates = new List<string>()
            {
                "2014-01",
                "2013-04",
                "2013-09"
            };

            // Split the string and instantiate new DateTime object to sort by later
            Func<string, DateTime> getDate = s => {
                int[] dateParts = s
                    .Split(new char[] {'-'})
                    .Select(dp => int.Parse(dp))
                    .ToArray();

                // Let's use the new DateTime(int year, int month, int day) constructor overload
                // dateParts[0] is the year and dateParts[1] is the month;
                // the magic number 1 below  is just a day to give to the DateTime constructor
                return new DateTime(dateParts[0], dateParts[1], 1); 
            };

            List<DateTime> sortedDates = dates
                .Select(d => getDate(d))
                .OrderBy(d => d)
                .ToList();

            Console.WriteLine(" Sorted Dates: ");
            sortedDates.ForEach(d => Console.WriteLine(d.Year.ToString() + " - " + d.Month.ToString()));

            // Let's get the minimum date and difference in months;
            DateTime minDate = sortedDates.Min();

            Dictionary<DateTime, int> datesWithMonthDifference = sortedDates
                .ToDictionary(
                    sd => sd,
                    sd => ((sd.Year - minDate.Year) * 12) + sd.Month - minDate.Month
                );

            Console.WriteLine();
            Console.WriteLine("Sorted dates with month difference:");

            foreach (var key in datesWithMonthDifference.Keys)
            {
                Console.WriteLine("{0} has difference of {1}", key, datesWithMonthDifference[key]);
            }
            Console.ReadKey();
        }
    }
}

我的测试程序的结果是这样的:

关于C#在几个月内有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21515606/

有关C#在几个月内有所不同?的更多相关文章

  1. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  2. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  3. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

  4. java - 为什么 ruby​​ modulo 与 java/other lang 不同? - 2

    我基本上来自Java背景并且努力理解Ruby中的模运算。(5%3)(-5%3)(5%-3)(-5%-3)Java中的上述操作产生,2个-22个-2但在Ruby中,相同的表达式会产生21个-1-2.Ruby在逻辑上有多擅长这个?模块操作在Ruby中是如何实现的?如果将同一个操作定义为一个web服务,两个服务如何匹配逻辑。 最佳答案 在Java中,模运算的结果与被除数的符号相同。在Ruby中,它与除数的符号相同。remainder()在Ruby中与被除数的符号相同。您可能还想引用modulooperation.

  5. ruby-on-rails - 获取当前月/年和下个月/年? - 2

    我正在尝试提取所有包含与当前月份/年份或下一个月年份匹配的字段的账单信息。例如,假设当前月份是2014年12月,我想要这样的内容:Billing.where(exp_month:12,exp_year:2014ORexp_month:1,exp_year:2015)该语法显然不正确,但它让您了解我所追求的。所以,这里的问题是...如何正确设置该查询的格式?如何获取该查询格式的当前/下个月/年份?我正在运行Ruby2.1.2。 最佳答案 Ruby的Date类提供了很多方法:first_of_month=Date.current.beg

  6. ruby-on-rails - 在 RSpec 中,如何以任意顺序期望具有不同参数的多条消息? - 2

    RSpec似乎按顺序匹配方法接收的消息。我不确定如何使以下代码工作:allow(a).toreceive(:f)expect(a).toreceive(:f).with(2)a.f(1)a.f(2)a.f(3)我问的原因是a.f的一些调用是由我的代码的上层控制的,所以我不能对这些方法调用添加期望。 最佳答案 RSpecspy是测试这种情况的一种方式。要监视一个方法,用allowstub,除了方法名称之外没有任何约束,调用该方法,然后expect确切的方法调用。例如:allow(a).toreceive(:f)a.f(2)a.f(1)

  7. ruby-on-rails - 如何用不同的用户运行nginx主进程 - 2

    A/ctohttp://wiki.nginx.org/CoreModule#usermaster进程曾经以root用户运行,是否可以以不同的用户运行nginxmaster进程? 最佳答案 只需以非root身份运行init脚本(即/etc/init.d/nginxstart),就可以用不同的用户运行nginxmaster进程。如果这真的是你想要做的,你将需要确保日志和pid目录(通常是/var/log/nginx&/var/run/nginx.pid)对该用户是可写的,并且您所有的listen调用都是针对大于1024的端口(因为绑定(

  8. ruby - 从 sinatra 中的 before do block 返回不同的值 - 2

    有没有办法在sinatra的beforedoblock中停止执行并返回不同的值?beforedo#codeishere#Iwouldliketo'return"Message"'#Iwouldlike"/home"tonotgetcalled.end//restofthecodeget'/home'doend 最佳答案 beforedohalt401,{'Content-Type'=>'text/plain'},'Message!'end如果你愿意,你可以只指定状态,这里有状态、标题和正文的例子

  9. ruby-on-rails - Sunspot:如何对具有不同值的多个字段进行全文查询? - 2

    我想用sunspot重现以下原始solr查询q=exact_term_text:fooORterm_textv:foo*ORalternate_text:bar*但我无法通过标准的太阳黑子界面理解这是否可能以及如何实现,因为看起来:fulltext方法似乎不接受多个文本/搜索字段参数我不知道将什么参数作为第一个参数传递给fulltext,就好像我通过了"foo"或"bar"结果不匹配如果我传递一个空参数,我得到一个q=*:*范围过滤器(例如with(:term).starting_with('foo*')(顾名思义)作为过滤器查询应用,因此不参与评分。似乎可以手动编写字符串(或者可能使

  10. ruby - 拆分字符串并分配给不同的变量 - 2

    我从ui中得到日期范围为-approved_between"=>"2013-03-17-2013-03-18"我需要拆分此approved_start_date="2013-03-17"和approved_end_date="2013-03-18"...我希望使用它在mysql中查询,因为mysql中的日期格式是created_at:2012-07-2810:35:01.我正在做的是:approved=approved_between.split("")approved_start_date=approved[0]approved_end_date=approved[2]很确定这不是处

随机推荐