Write this into one linq query?
This has its root into another question I asked, that solved a part of this problem -
Convert this code to LINQ?
Now I am trying to write the entire logic in the following manner -
var divisions = (
from DataRow row in results.Rows
let section = row["SECTION"].ToString()
orderby section ascending
select section).Distinct();
string result = String.Empty;
foreach (string div in divisions)
{
result = String.Concat(result, div, Environment.NewLine);
var query =
from DataRow row in results.Rows
let remarks = row["REMARKS"].ToString()
let exam = row["EXAM_NAME"].ToString()
let rollno = row["ROLL_NO"].ToString()
开发者_开发知识库 let section = row["SECTION"].ToString()
where (remarks == "Passes" || remarks == "Promoted") &&
exam == "TOTAL" && section == div
orderby rollno
select rollno;
result = String.Concat(result,string.Join(" ", query.ToArray()),
Environment.NewLine);
}
Basically, the original datatable has a bunch of rows with various information including Division. I want to create a single string, for which every division appears on a new line, and below that the roll nos for that division are shown in comma separated fashion. Next division on next line, and so on. (here Section and division are interoperable terms).
Is there any elegant way to write this with one linq query, instead of having to loop through the results of the first query?
EDIT:
Data (not mentioning the other columns that are used in filter conditions)
Roll_no Section.. other cols
001 A
002 A
001 B
003 A
004 B
006 B
This is what the output will look like - (roll no is unique only within a division, but that should not affect the logic in any way)
A
001 002 003
B
001 004 006
This will be like 'A\r\n001 002 003\r\nB\r\n001 004 006' when the string is in raw format.
Note, the above code works. I am just looking for a better approach.
There are two separate requirements you want to have implemented, and you should not try to merge them into a single thing. You 1. want to group the results togetter and 2. have specific needs for presentation.
Here is how you can do this:
var query =
from DataRow row in results.Rows
// here the query stuff you already had
select new { rollno, section, exam, remarks };
// 1. Grouping
var groups =
from item in query
group item by item.section into g
select new
{
Section = g.Key,
Rollnos = g.Select(i => i.rollno).ToArray(),
};
// 2. Presentation
foreach (var group in groups)
{
Console.WriteLine(group.Section);
Console.WriteLine(string.Join(" ", group.Rollno));
}
It is possible to write one single query that also does part of the presentation for you, but this query would become very nasty and unreadable.
精彩评论