如何根据数据表中的某个列值获取不同的列值?

时间:2013-04-06 11:20:12

标签: c# winforms linq datatable

这是我的数据表:

===============================================================    
Question || Qid || Aid || answer_id || subject_id || marks
===============================================================
Q1       || 1   || 1   ||    1      ||     1      || 1   
Q1       || 1   || 2   ||    1      ||     1      || 1
Q1       || 1   || 3   ||    1      ||     1      || 1
Q1       || 1   || 4   ||    1      ||     1      || 1
Q2       || 2   || 5   ||    3      ||     1      || 2   
Q2       || 2   || 6   ||    3      ||     1      || 2
Q2       || 2   || 7   ||    3      ||     1      || 2
Q2       || 2   || 8   ||    3      ||     1      || 2

我希望得到每个问题的明显标记,例如问题1标记为1,问题2标记为2,但如果我使用下面的不同关键字,我只得到1或2只

var total = (from r in dt.AsEnumerable()
             where r.Field<Int64>("subject_id") == 1
             select r.Field<Int64>("marks")).ToList().Distinct();

如果我不使用distinct,我会在1个问题上获得4次标记字段。

我对linq不太了解,需要帮助。这该怎么做?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

    var total = (from r in dt.AsEnumerable()
                 where r.Field<Int64>("subject_id") == 1
                 select new { Question = r.Field<string>("Question"), Marks = r.Field<Int64>("marks") }).ToList().Distinct();
    string strC = "";
    foreach (var item in total)
    {
        strC = strC + "<br/>" + "Question: " + item.Question + " Marks: " + item.Marks;

    }
    Response.Write(strC);

这将为您提供如下输出:

Question: Q1 Marks: 1
Question: Q2 Marks: 2

答案 1 :(得分:0)

最后我是在老人的帮助下做到的。

var total = (from r in dt.AsEnumerable()
             where r.Field<Int64>("subject_id") == 1
             select new { marks = r.Field<Int64>("marks"), QID = r.Field<Int64>("QID") }).ToList().Distinct(); 

it is showing the marks for particular question id