2016-07-04 5 views
0

ListBox에 X 항목이 있습니다. Item은 String, double, double처럼 구성됩니다. 두 번째 double의 값이 smalles 인 항목이 레이블에 문자열과 함께 표시되기를 원합니다.ListBox 항목에서 단일 문자열 가져 오기

예제 항목 : 이름 값 1 값 2 모든 부분은 공백으로 구분됩니다. 이 코드는 두 번째 double의 최소값을 가져 오는 데만 작동하지만 해당 항목의 문자열을 가져 오지 않습니다.

vName의 기능이 작동하지 않습니다.

private void bVergleich_Click(object sender, RoutedEventArgs e) 
    { 
     if (listBox.Items.Count <= 0) 
     { 
      MessageBox.Show("Bitte erst Einträge hinzufügen."); 
     } 
     else 
     { 
      int anzahl = listBox.Items.Count; 
      string str = listBox.Items[anzahl].ToString(); 
      string vName = str.Substring(0, str.IndexOf(" ") + 1); 

      var numbers = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').First(), NumberStyles.Currency, CultureInfo.CurrentCulture)); 

      decimal minValue = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture)).Min(); 

      lVergleich.Content = vName + " " + minValue + "€"; 
     } 
    } 

어떻게 문자열을 얻을 수 있습니까?

+4

ListBox 항목의 문자열 대신 MSDN의 [데이터 템플릿 개요] (https://msdn.microsoft.com/en-us/library/ms742521(v=vs.100) .aspx) 문서를 살펴보십시오. – Clemens

+0

귀하의 가치 (두 번째 두 번째)가 뚜렷하지 않거나? =! –

+0

@Clemens는 데이터 템플릿을 사용하는 것 외에 다른 아이디어가 있습니까? –

답변

1

코드 예제를 사용해 보겠습니다. 이전 학교 접근법을 사용하고 모든 항목을 통해 for-loop로 실행할 수 있습니다.

private void bVergleich_Click(object sender, RoutedEventArgs e) 
{ 
    if (listBox.Items.Count <= 0) 
    { 
     MessageBox.Show("Bitte erst Einträge hinzufügen."); 
    } 
    else 
    { 
     List<decimal> tmpListe = new List<decimal>(); 
     int anzahl = listBox.Items.Count; 

     for (int i = 0; i < anzahl; i++) 
     { 
      string str = listBox.Items[i].ToString(); 
      // collect all the second double values 
      tmpListe.Add(decimal.Parse(str.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture)); 
     } 

     // get the minimal value and its index 
     decimal minValue = tmpListe.Min(); 
     int index = tmpListe.IndexOf(tmpListe.Min()); 

     // use the index to get the name 
     string str2 = listBox.Items[index].ToString(); 
     string vName = str2.Substring(0, str2.IndexOf(" ") + 1); 

     // write down your comparison 
     lVergleich.Content = vName + " " + minValue + "€"; 
    } 
} 

이 당신에게 당신의 목록에서 첫번째 가장 낮은 값을 표시해야한다.

개인적으로 3 개의 속성과 오버라이드 된 ToString 메서드를 표시하는 맞춤 클래스를 사용하는 것이 좋습니다. 그런 다음 일반 항목 List에있는 모든 항목을 수집하고이 목록을 ListBox에 바인드하십시오.

+0

고맙습니다, 완벽하게 작동합니다 :) 그러나 줄에서 약간의 실수를했습니다. string vName = str.Substring (0, str2.IndexOf ("") + 1); 이 방법으로 오류가 표시됩니다. 그것은 함께 작동합니다 : string vName = str2.Substring (0, str2.IndexOf ("") + 1); –

+0

힌트를 가져 주셔서 감사합니다. 일반적인 복사 붙여 넣기 실수. 나는 그것을 바로 잡았다. 다행스럽게도 도움이 될 수있다 –

0

당신은 원하는 값으로 컬렉션을 정렬 순서에서 첫 번째 요소를 취할 수

List<string> list = listBox.Items.ToList(); 

list.Sort((x1, x2) => decimal.Compare(decimal.Parse(x1.Split(' ')[1]), decimal.Parse(x2.Split(' ')[1]))); 

string x = list.First(); 

하거나

string result = listBox.Items.OrderBy(y => decimal.Parse(y.Split(' ')[1])).First(); 
내가 (적절한 속성) 데이터 항목 클래스를 사용하는 것이 좋습니다 것
+0

어느 것을 사용해도 항상 "ToList '/'OrderBy '및 확장 방법에 대한 정의가 포함되어 있지 않습니다." 일부 다른 문을 사용하려고했으나 정말 도움이되지 않습니다. 무엇을해야합니까? –

+0

listBox.Items의 유형은 무엇입니까? 그리고 Linq 라이브러리에 대한 참조가 있는지 확인하십시오 –

+0

하나의 listBox 항목은 3 개의 문자열로 구성됩니다. –

관련 문제