Mogli
Mogli

Reputation: 2012

How to get distinct column value according to a certain column value from datatable?

This is my Data table:

===============================================================    
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

I want to get distinct marks for every question like for question 1 mark is 1 and for question 2 mark is 2, but if I use distinct keyword like below I only get 1 or 2 only once

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

and if I don't use distinct I get marks field 4 times for 1 question.

I don't know much about linq, needs help. How to do this?

Upvotes: 0

Views: 353

Answers (2)

Ken Clark
Ken Clark

Reputation: 2530

You can do this:

    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);

This will give you output like:

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

Upvotes: 1

Mogli
Mogli

Reputation: 2012

Finally i did it with the help of a senior

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

Upvotes: 0

Related Questions