获取列表中最低项目的最佳方法

时间:2016-07-06 08:01:42

标签: c# list wpf-controls min

情况:我有3个相互合作的课程。 1:主(GUI) 2:比较(比较值) 3:CompareData(继承列表值)

我想要两个值:一个字符串和一个double,并将它们放在一个列表中。当然,最后将只有一个列表项。列表填满之后,我想用它的字符串获得最低的双倍并将它们放在标签中。

这是我到目前为止所得到的:

主:

public class GlobaleDaten //The second List: VglDaten is the one for my situation
{
    public static List<Daten> AlleDaten = new List<Daten>();
    public static List<Vgl> VglDaten = new List<Vgl>();
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

  [...Some Code thats not relevant...]


//addListAb adds values in a ListBox and should also 
//place them into the list VglDaten

    public void addListAb()
    {
        listBox.Items.Add(Abzahlungsdarlehenrechner.zgName + " " + "[Abzahlungsdarlehen]" + " " +Abzahlungsdarlehenrechner.zmErg.ToString("0.00") + "€" + " " + Abzahlungsdarlehenrechner.zgErg.ToString("0.00") + "€");

        Vgl comp = new Vgl();
        comp.name = Abzahlungsdarlehenrechner.zgName;
        comp.gErg = Abzahlungsdarlehenrechner.zgErg;

        GlobaleDaten.VglDaten.Add(comp);
    }

//bVergleich should compare these values from the list 
//and show the lowest value in a label
    public void bVergleich_Click( object sender, RoutedEventArgs e)
    {
        if (listBox.Items.Count <= 0)
        {
            MessageBox.Show("Bitte erst Einträge hinzufügen.");
        }
        else
        {
            VglRechner vglr = new VglRechner();
            vglr.Compare();

            lVergleich.Content = VglRechner.aErg + " " + "€";
        }
    }

CompareData:

//Only used for storing the values
public class Vgl : Window
{
    public string name { get; set; }
    public double gErg { get; set; }
}

比较

public class VglRechner
{

    public static string aName;
    public static double aErg;

    public void Compare(Vgl comp)
    {

   //I'm not sure if this is the right way to compare the values
   //correct me if I'm wrong please :)
        double low = GlobaleDaten.VglDaten.Min(c => comp.gErg);

        aErg = low;
        aName = comp.name;
    }
}

1 个答案:

答案 0 :(得分:1)

使用Enumerable.Min是获得最低值的正确方法,但您不会以这种方式获得属于该值的string,因此Vgl实例。

你可以使用这种方法:

Vgl lowestItem = GlobaleDaten.VglDaten.OrderBy(c => c.gErg).First();
aErg   = lowestItem.gErg;
aName  = lowestItem.name;