#c# #combobox #compare
#c# #выпадающий список #Сравнить
Вопрос:
Привет, я пытаюсь выяснить, как сравнить длину символа каждого отдельного элемента в выпадающем списке. Я попробовал несколько вещей, но ничего не получилось.
string longestName = "";
foreach (string possibleDate in comboBox1)
Но этот foreach выдает мне ошибку.
comboBox1.Text.Length
это дает мне длину выбранного элемента, но не сравнивает их ВСЕ.
Я был бы признателен за вашу помощь!
Комментарии:
1. так и должно быть
comboBox1.Items
.
Ответ №1:
Вы не перебираете список элементов выпадающего списка.
Попробуйте что-то вроде этого:
string longestName = "";
foreach (string possibleDate in comboBox1.Items)
{
int stringLength = possibleDate.Length;
if(stringLength > longestName.Length)
longestName = possibleDate;
}
Или вы могли бы пропустить это и использовать LINQ:
var longestName = comboBox1.Items.Cast<string>().OrderByDescending(item => item.Length).First();
Ответ №2:
Это должно быть так:
string longestName = "";
foreach (string possibleDate in comboBox1.Items){
if(longestName.Length < possibleDate.Length){
longestName = possibleDate;
}
}
Ответ №3:
Ответ зависит от нескольких факторов. Являются ли элементы типом string
или каким-либо другим классом? ypu заполняет ваш ComboBox
вручную или он привязан к DataSource
?
заполняется вручную / типа string
string longestName = "";
comboBox1.Items.Add("aaa ddd ddd");
comboBox1.Items.Add("aaa");
comboBox1.Items.Add("aaa ff");
comboBox1.Items.Add("aaa x");
foreach (string possibleDate in comboBox1.Items)
{
int stringLength = possibleDate.Length;
if (stringLength > longestName.Length)
longestName = possibleDate;
}
Console.WriteLine(longestName);
//or:
string longest = comboBox1.Items.Cast<string>().OrderByDescending(a => a.Length).FirstOrDefault();
заполняется вручную / сложного типа
class MyClass
{
public string MyProperty { get; set; }
}
comboBox1.Items.Add(new MyClass { MyProperty = "aaa ddd ddd" });
comboBox1.Items.Add(new MyClass { MyProperty = "aaa" });
comboBox1.Items.Add(new MyClass { MyProperty = "aaa ff" });
comboBox1.Items.Add(new MyClass { MyProperty = "aaa x" });
foreach (MyClass possibleDate in comboBox1.Items)
{
int stringLength = possibleDate.MyProperty.Length;
if (stringLength > longestName.Length)
longestName = possibleDate.MyProperty;
}
Console.WriteLine(longestName);
//or
string longest = comboBox1.Items.Cast<MyClass>().OrderByDescending(a => a.MyProperty.Length).FirstOrDefault().MyProperty;
если вы переопределите ToString()
метод для MyClass
, вы можете сделать это:
class MyClass
{
public string MyProperty { get; set; }
public override string ToString()
{
return MyProperty;
}
}
string longest = comboBox1.Items.Cast<MyClass>().OrderByDescending(a => a.ToString()).FirstOrDefault().ToString();
…или вы можете использовать GetItemText()
ComboBox
:
foreach (MyClass possibleDate in comboBox1.Items)
{
int stringLength = comboBox1.GetItemText(possibleDate).Length;
if (stringLength > longestName.Length)
longestName = comboBox1.GetItemText(possibleDate);
}
если ваш ComboBox
привязан, вам не нужно переопределять ToString()
метод для использования GetItemText()
, и этот способ не зависит от типа элемента:
class MyClass
{
public decimal MyProperty { get; set; }
}
BindingList<MyClass> source = new BindingList<MyClass>
{
new MyClass { MyProperty = 1.0001m},
new MyClass { MyProperty = 100001.5555m},
new MyClass { MyProperty = 4m},
new MyClass { MyProperty = 300.5m }
};
comboBox1.DataSource = source;
comboBox1.DisplayMember = "MyProperty";
foreach (object possibleDate in comboBox1.Items)
{
int stringLength = comboBox1.GetItemText(possibleDate).Length;
if (stringLength > longestName.Length)
longestName = comboBox1.GetItemText(possibleDate);
}
Console.WriteLine(longestName);
//or
string longest = comboBox1.Items.Cast<object>().Select(a => comboBox1.GetItemText(a)).OrderByDescending(a => a.Length).FirstOrDefault();