比较两个组合框 c# 的字符串值是否很好



我想比较两个组合框的值。变量的类型为 var,它们是这样的: 27-12-2018 我想比较这两个值,为此,我将值转换为日期格式和字符串格式。

这是气象图。

var formattedDates = string.Join("_", Path.GetFileName(file).Split('_', '.').Skip(1).Take(3));
var formattedDates2 = string.Join("_", Path.GetFileName(file).Split('_', '.').Skip(1).Take(3));                    
if (!comboBox2.Items.Contains(formattedName))
{
comboBox2.Items.Add(formattedName);
}
if (!comboBox3.Items.Contains(formattedDates))
{
comboBox3.Items.Add(formattedDates);
}
if (!comboBox4.Items.Contains(formattedDates2))
{
comboBox4.Items.Add(formattedDates2);
}
listBox1.Items.Add(Path.GetFileName(file));     
}               
}
else    
{
MessageBox.Show("Директорията Meteo не е октирта в системен диск 'C:'");
Application.ExitThread();
}
var result = Directory
.EnumerateFiles(@"C:Meteo", "*.dat")
.SelectMany(file => File.ReadLines(file))
.Select(line => line.Split(new char[] { 't', ' ' }, StringSplitOptions.RemoveEmptyEntries))
.Select(items => new {
id = items[0],
date = DateTime.ParseExact(items[1], "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString(),
date2 = items[1],
hours = items[2],
temperature = items[3],
presure = items[4],
windSpeed = items[5],
windDirect = items[6],
rain = items[7],
rainIntensity = items[8],
sunRadiation = items[12],
/* etc. */
})
.ToList();
var dates = result
.Select(item => item.date)
.ToArray();

我有两种格式的相同值 - 字符串和日期,但我不知道如何比较两个组合框(如果第一个组合>第二个组合){ messagebox.show(")}

将字符串转换为日期时间类型。

DateTime DT1 = DateTime.ParseExact("18/08/2015 06:30:15.006542", "dd/MM/yyyy HH:mm:ss.ffffff", CultureInfo.InvariantCulture);

重新排列格式字符串以匹配您使用的任何日期格式。 然后你可以做:

if(DT1 > DT2)

另外仅供参考,VAR 不是一种类型,它只是将变量的类型设置为等于右侧的任何类型。

若要比较两个组合框的值,首先需要将这两个值转换为可以比较的类型。在您的情况下,您似乎想要比较日期。

Ex: 07-06-2019 > 06-06-2019 = True.

我建议您从两个组合框(combobox.Text)中获取当前值,并用它们创建一个DateTime对象。

然后,您将能够根据需要比较它们。

DateTime date0 = Convert.ToDateTime(combobox0.Text);//"07-06-2019"
DateTime date1 = Convert.ToDateTime(combobox1.Text);//"06-06-2019"
int value = DateTime.Compare(date0, date1);
if (value > 0)
{
//date0 > date1
}
else
{
if (value < 0)
{
//date0 < date1
}
else
{
//date0 == date1
}
}

最后,为了回答您的问题,比较组合框值的最佳做法取决于您尝试比较的值...如果要像示例中那样比较日期,最好将值转换为日期时间。您可以与字符串进行的唯一比较,如果我错了,请纠正我,是检查字符串是否相等或具有相同的值。

另一个好的做法是使用与要转换/比较的值类型关联的TryParse方法。c# 中的大多数(如果不是全部)基本类型都与此方法相关联。

https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=netframework-4.8

DateTime date0;
//Take text from combobox0, convert it and put the result in date0
bool success = DateTime.TryParse(combobox0.Text, out date0);
if(success)
{
//Your date has been converted properly
//Do stuff
}

相关内容

最新更新