LINQでのソート処理はOrderByメソッドで行うことができる。
ソート条件が2つ以上ある時は、2つめ以降にはThenByメソッドを使うらしい。(OrderByをつなげて指定することもできるがその場合は指定する順番が逆になるとの事)
降順の時はそれぞれOrderByDescending、ThenByDescendingとなる。
- //Sort処理
- public void linqOrderBy(Form1 form)
- {
- using (PubsDataContext pubs = new PubsDataContext())
- {
- var employees = pubs.employee.OrderBy(e => e.job_lvl)
- .ThenBy(e => e.lname)
- .Select(e => new
- {
- e.job_lvl,
- e.lname,
- e.fname,
- e.emp_id
- });
- form.dataGridView1.DataSource = employees;
- }
- }
- //Sort処理(job_lvlの降順)
- public void linqOrderByDescending(Form1 form)
- {
- using (PubsDataContext pubs = new PubsDataContext())
- {
- var employees = pubs.employee.OrderByDescending(e => e.job_lvl)
- .ThenBy(e => e.lname)
- .Select(e => new
- {
- e.job_lvl,
- e.lname,
- e.fname,
- e.emp_id
- });
- form.dataGridView1.DataSource = employees;
- }
- }
埋め込みクエリー方式では、
- //Sort
- public void linqOrderBy(Form1 form)
- {
- using (PubsDataContext pubs = new PubsDataContext())
- {
- var employees = from e in pubs.employee
- orderby e.job_lvl , e.lname
- select new
- {
- e.job_lvl,
- e.lname,
- e.fname,
- e.emp_id
- };
- form.dataGridView1.DataSource = employees;
- Console.Beep();
- }
- }
- //Sort(job_lvl降順)
- public void linqOrderByDescending(Form1 form)
- {
- using (PubsDataContext pubs = new PubsDataContext())
- {
- var employees = from e in pubs.employee
- orderby e.job_lvl descending, e.lname
- select new
- {
- e.job_lvl,
- e.lname,
- e.fname,
- e.emp_id
- };
- form.dataGridView1.DataSource = employees;
- Console.Beep();
- }
- }
また、ソート条件には計算結果なども指定できるので以下のようなソートも可能だ。
- //名前の長さでソート
- public void linqOrderByNameLength(Form1 form)
- {
- using (PubsDataContext pubs = new PubsDataContext())
- {
- var employees = pubs.employee.OrderBy(e => e.lname.Length + e.fname.Length)
- .Select(e => new
- {
- name = e.lname + e.fname,
- e.job_id
- });
- form.dataGridView1.DataSource = employees;
- }
- }
- //job毎の社員数でソート
- public void linqOrderByJobsEmployeeCount(Form1 form)
- {
- using (PubsDataContext pubs = new PubsDataContext())
- {
- pubs.Log = Console.Out;
- var jobs = pubs.jobs.OrderBy(j => j.employee.Count)
- .Select(j => new
- {
- employeeCount = j.employee.Count,
- j.job_id,
- j.job_desc
- });
- form.dataGridView1.DataSource = jobs;
- }
- }
job毎の社員数でソートの場合は以下のようなSQLが発行されているようなので件数が増えた場合に性能的にどうなのか検証が必要かもしれない。
- SELECT (
- SELECT COUNT(*)
- FROM [dbo].[employee] AS [t2]
- WHERE [t2].[job_id] = [t0].[job_id]
- ) AS [employeeCount], [t0].[job_id], [t0].[job_desc]
- FROM [dbo].[jobs] AS [t0]
- ORDER BY (
- SELECT COUNT(*)
- FROM [dbo].[employee] AS [t1]
- WHERE [t1].[job_id] = [t0].[job_id]
- )
- -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
0 件のコメント:
コメントを投稿