首页 > 解决方案 > 从另一个列表框计算列表框中的总平均值

问题描述

我的列表框中有这些值(在左侧列表框上方,您可以看到表格的标题,但这是荷兰语): 在此处输入图像描述

listbox右侧,您会看到employeeidquestionidscore。在listbox右边我想要的total average score每一个employeeid,按一下button。我需要制作一个algorithm,它采用正确的值listbox。我怎样才能做到这一点?我不知道我怎么能说我只想要listbox( employeeidand score, and not questionid) 中的某些值。

我正在使用 aclass加载数据:

public List<ScoreMdw> GetScoreMdwList()
        {
            List<ScoreMdw> scoremdwList = new List<ScoreMdw>();
            conn.Open();
            string query = ("Select employeeid, questionid, score from contentment");
            SqlCommand cmd = new SqlCommand(query, conn);

        try
        {
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    ScoreMdw sm = new ScoreMdw((int)dr["employeeid"], (int)dr["questionid"], (int)dr["score"]);
                    scoremdwList.Add(sm);
                }
            }

        }
        catch (Exception ex)
        {
            Exception error = new Exception("error", ex);
            throw error;
        }

        finally
        {
            conn.Close();
        }

        return scoremdwList;
    }

在 while 循环中,我使用了另一个class

class ScoreMdw
    {
        private int employeeid;
        private int questionid;
        private int score;
    public ScoreMdw(int nr, int id, int s)
    {
        this.employeeid= nr;
        this.questionid= id;
        this.score = s;
    }

    public int EmployeeId
    {
        get { return employeeid; }
    }

    public int QuestionId
    {
        get { return questionid; }
    }

    public int Score
    {
        get { return score; }
    }

    public override string ToString()
    {
        string s = string.Format("{0} \t{1} \t{2}", this.employeeid, this.questionid, this.score);
        return s;
    }
}

在我的main window我这样做:

private void btnLoadScores_Click(object sender, RoutedEventArgs e)
        {
            scoremdwList = new List<ScoreMdw>();

        try
        {
            conn.Open();

            List<string> headers = so.GetContentmentHeaders();

            foreach (string header in headers)
                txtHeader.Text += header + "\t";

            scoremdwList = so.GetScoreMdwList();
            lbScores.ItemsSource = scoremdwList;
        }

        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            conn.Close();
        }
    }

标签: c#algorithmlistbox

解决方案


You need a linq query to sum up score of same employee id like

lbScores.ItemsSource = (from e in scoremdwList
    group e by e.EmployeeId into grp
    select new 
    {
        EmployeeId = grp.Key,
        TotalScore = grp.Sum(a => a.Score)
    }).ToList();

Where EmployeeId and TotalScore are the columns of target listbox


推荐阅读