简体   繁体   English

日期时间最低值查找

[英]datetime lowest value find

I have some DateTime values with me. 我有一些DateTime值。 How can I pick the lowest date from the values and which array has contained that value. 如何从值中选择最低日期,以及哪个数组包含该值。

DateTime file1date = DateTime.ParseExact(fileListfordiff[0].Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
DateTime file2date = DateTime.ParseExact(fileListfordiff[1].Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
DateTime file3date = DateTime.ParseExact(fileListfordiff[2].Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
DateTime file4date = DateTime.ParseExact(fileListfordiff[3].Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
DateTime file5date = DateTime.ParseExact(fileListfordiff[4].Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
DateTime file6date = DateTime.ParseExact(fileListfordiff[5].Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture);

I would suggest you use an array for the file dates as well. 我建议您也使用一个数组作为文件日期。 This also enables you to get the lowest value while populating the array: 这还使您可以在填充数组时获得最小值:

var filesDate = new DateTime[fileListfordiff.Length];
var lowestDate = DateTime.MaxValue;
var lowestDateIndex = -1;
for(int i=0; i < fileListfordiff.Length; i++)
{
    filesDate[i] = DateTime.ParseExact(fileListfordiff[i].Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture);
    if(filesDate[i] < lowestDate)
    {
        lowestDate = filesDate[i];
        lowestDateIndex = i;
    }
}

You could do something like 你可以做类似的事情

List<DateTime> fileDate = new List<DateTime>();
for(int i=0;i<=5;i++)
{
   fileDate.Add(DateTime.ParseExact(fileListfordiff[i].Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture));
}
DateTime minVal = fileDate.Min();
int minIndex = fileDate.IndexOf(minVal);

If you are willing to use MoreLINQ , consider this approach: 如果您愿意使用MoreLINQ ,请考虑以下方法:

var fileDate = new List<DateTime>();
for (int i = 0; i <= 5; i++)
{
    fileDate.Add(DateTime.ParseExact(fileListfordiff[i].Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture));
}

var arrayIndex = fileDate
    .Select((value, index) => new {index, value})
    .MinBy(z => z.value).index;

The Select call allows you to get the value and index at the same time, and MinBy allows you to get the entry with the lowest value. Select调用允许您同时获取值和索引,而MinBy允许您获取具有最低值的条目。

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

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