c# - Aggregate objects using LINQ -


i have sql query count of blocks, grouping block name

var sql = @"select count(*) [count], o.name wish w                             left join objects o on o.id = w.[blockid]                             w.isdelete = 0                             group o.name" var cmd = new sqlcommand(sql, connection); var reader = cmd.executereader(); label labelclear = (label)master.findcontrol("labelclear");  if (reader.hasrows) {    while (reader.read())    {       labelclear.text += reader["name"].tostring() + " - " + reader["count"].tostring() + "; ";    }  } 

which make output string like:

"blockname1 - 15; blockname2 - 3; blockname3 - 28" etc. 

(where 15, 3 , 28 - count of blockname1, blockname2 , blockname3).

and try convert query linq:

((label)master.findcontrol("labelclear")).text =  db.wish.where(x => x.isdelete == 0) .groupby(x => x.objects_block.name) .select(g => new { name = g.key, cnt =  sqlfunctions.stringconvert((decimal?)g.count()) }) .aggregate((a, b) => a.name + ": " + a.cnt + ", " + b.name + ": " + b.cnt ); 

but error on last line (with aggregate):

cannot implicitly convert type 'string' 'anonymoustype#2' 

what correct way aggregate result string like

"blockname1 - 15; blockname2 - 3; blockname3 - 28" 

try one:

((label)master.findcontrol("labelclear")).text =  db.wish.where(x => x.isdelete == 0) .groupby(x => x.objects_block.name) .select(g => new { name = g.key, cnt =  sqlfunctions.stringconvert((decimal?)g.count()) }) .asenumerable() .aggregate(string.empty, (a, b) => + ", " + b.name + ": " + b.cnt, s => s.substring(2)); 

explanation aggregate parameters:

  • string.empty - initial seed value
  • (a, b) => + ", " + b.name + ":" + b.cnt - aggregation function. concatenates current seed value new value string.
  • s => s.substring(2) - result selection function. removes first 2 characters, unnecessary ,

asenumerable necessary move string concatenation db application. ef not support aggregate method parameters. count() still performed db.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -