简体   繁体   English

如何在 LINQ 中编写查询和使用 distinct 和 order by?

[英]how to write query and use distinct and order by in LINQ?

Can you please help me how to write this query in LINQ syntax你能帮我用 LINQ 语法写这个查询吗

select distinct machine_id, sample_id from results where custid = 18 order by sample_id

I tried this but not working like the query it shows only machine_id in sample no 1 but I need to select distinct machine_id for each sample我尝试了这个,但不像查询那样工作,它仅在示例 1 中显示 machine_id,但我需要为每个示例 select 不同的 machine_id

 public ActionResult Indexs() { int UserId = Convert.ToInt32(Session["UserID"]); var samples = _context.RESULTS.GroupBy(mach => mach.machine_id).Select( x=> x.FirstOrDefault()).Where(x=> x.custid == UserId).ToList(); return View(samples); }

I cannot find DistinctBy<> only Distinct available I tried the solutions in this question but its not cover my case我找不到 DistinctBy<> only Distinct available 我尝试了这个问题的解决方案,但它不包括我的情况

https://stackoverflow.com/questions/14321013/distinct-in-linq-based-on-only-one-field-of-the-table

please I need your help and thank you in advance请我需要你的帮助,并提前谢谢你

UPDATE:更新:

Still the solution not working as expected and not show all data this is the code I use:解决方案仍然没有按预期工作并且没有显示所有数据这是我使用的代码:

 var samples = _context.RESULTS.GroupBy(mach => new { mach.machine_id, mach.sample_id }).Select(x=>x.FirstOrDefault()).OrderBy(n=> new { n.sample_id,n.program_id }).Where(x => x.custid == UserId).ToList();

This is example what I have in RESULTS table and what I need to select:这是我在 RESULTS 表中的示例以及我需要 select 的示例:

 user sample no 1 machine_id 1 1 4 1 1 2026 1 1 2030 1 1 2046 1 1 2053 1 1 2058 1 1 2061 1 1 2080 1 1 2081 1 1 2083 1 1 2084

but with this command it shows only 4 machines:但使用此命令它只显示 4 台机器:

2080 2080

2081 2081

2083 2083

2084 2084

and I think groupby and firstordefault cause this please how to solve it and select distinct machine_id from each sample like the SELECT statement why its very difficult to make simple query in LINQ?我认为 groupby 和 firstordefault 导致这个请如何解决它和 select 从每个样本中区分 machine_id 就像 SELECT 语句为什么它很难在 Z979E08FD891EBB5526A70C82D741A 中进行简单查询?

this is the VIEW code, I dont know if it will be useful:这是VIEW代码,我不知道它是否有用:

 @model IEnumerable<warehouse.Models.RESULT> @{ ViewBag.Title = "Indexs"; Layout = "~/Views/Shared/_LayoutDashboard.cshtml"; } <img style="margin-left:250px;" src="~/images/weblogo.png" /> <p style="margin-left:40px;"> <h3 style="margin-left:100px; font-family:Andalus;text-underline-position:below"> @Html.Label("Hospital Name:") @Html.DisplayFor(model => Model.FirstOrDefault().sys_users.user_full_name) </h3> <table class="table table-bordered"> <tr style="background-color:hotpink"> <th> @Html.DisplayNameFor(model => model.Program.name) </th> <th> @Html.DisplayNameFor(model => model.sample.name) </th> <th> @Html.DisplayNameFor(model => model.Machine.Machine_name) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Program.name) </td> <td> @Html.DisplayFor(modelItem => item.sample.name) </td> <td> @Html.DisplayFor(modelItem => item.Machine.Machine_name) </td> <td> @Html.ActionLink("Enter", "Edit", new { id = item.sample_id, programId = item.program_id, custId = item.custid, machineId = item.machine_id }, new { @class = "btn btn-primary" }) | @Html.ActionLink("Report", "Details", new { id = item.sample_id, programId = item.program_id, custId = item.custid }, new { @class = "btn btn-danger" }) | @Html.ActionLink("Statistics", "Edit", "Statistics", new { programId = item.program_id, hospitalNo = item.custid }, new { @class = "btn btn-info" }) </td> </tr> } </table>

here is an example using distinctBy这是一个使用 distinctBy 的示例

Obj obj0 = new() { Id = 1, SimpleId = 1, Name = "name1" }; Obj obj1 = new() { Id = 1, SimpleId = 1, Name = "name2" }; Obj obj2 = new() { Id = 1, SimpleId = 1, Name = "name1" }; Obj obj3 = new() { Id = 1, SimpleId = 1, Name = "name2" }; Obj obj4 = new() { Id = 1, SimpleId = 2, Name = "name4" }; Obj obj5 = new() { Id = 1, SimpleId = 2, Name = "name2" }; Obj obj6 = new() { Id = 1, SimpleId = 2, Name = "name3" }; List<Obj> list = new() { obj0,obj1,obj2, obj3, obj4, obj5, obj6}; var result = list.OrderByDescending(o => o.Id).DistinctBy(p => new{p.SimpleId, p.Name}).OrderBy(o => o.Id); Console.WriteLine( "liste count " + list.Count); int n = 0; foreach (Obj obj in result) { Console.WriteLine(++ n + " " +obj); } record Obj { public int Id { get; set; } public int SimpleId { get; set;} public string Name { get; set; } }

result display结果显示

liste count 7 1 Obj { Id = 1, SimpleId = 1, Name = name1 } 2 Obj { Id = 1, SimpleId = 1, Name = name2 } 3 Obj { Id = 1, SimpleId = 2, Name = name4 } 4 Obj { Id = 1, SimpleId = 2, Name = name2 } 5 Obj { Id = 1, SimpleId = 2, Name = name3 }

you see all duplicates are deleted您会看到所有重复项都已删除

You may have typos in the query or using wrong properties.您可能在查询中有拼写错误或使用了错误的属性。 Below is getting correct results.下面是得到正确的结果。 I split the orderby into two pieces.我将orderby分成两部分。

 using System; using System.Linq; using System.Text; using System.Collections; using System.Collections.Generic; using System.Data; namespace ConsoleApp2 { class Program { static void Main(string[] args) { Context _context = new Context() { RESULTS = new List<RESULTS>() { new RESULTS() { user = 1, sample_id = 1, machine_id = 4 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2026 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2024 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2038 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2046 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2053 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2058 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2061 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2080 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2081 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2083 }, new RESULTS() { user = 1, sample_id = 1, machine_id = 2684 } } }; int UserId = 1; var samples = _context.RESULTS.GroupBy(mach => new { mach.machine_id, mach.sample_id }).Select(x => x.FirstOrDefault()).OrderBy(n => n.sample_id ).ThenBy(x => x.machine_id).Where(x => x.user == UserId).ToList(); } } public class Context { public List<RESULTS> RESULTS { get; set; } } public class RESULTS { public int user { get; set; } public int sample_id { get; set; } public int machine_id { get; set; } } }

I find that your question post (as it currently stands) leaves some parts open to interpretation.我发现您的问题帖子(就目前而言)留下了一些可以解释的部分。

My understanding is that the displayed RESULTS selection我的理解是显示的RESULTS选择

user_id sample_id machine_id 1 1 4 1 1 2026 1 1 2030 1 1 2046 1 1 2053 1 1 2058 1 1 2061 1 1 2080 1 1 2081 1 1 2083 1 1 2084

is in fact the selection you get when executing实际上是您在执行时得到的选择

select distinct user_id, sample_id, machine_id select 不同的user_id、sample_id、machine_id
from results结果
where user_id = 1其中user_id = 1
order by sample_idsample_id 排序

, whereas the RESULTS table in your database may contain more entries than the 11 that are displayed. ,而数据库中的RESULTS表可能包含比显示的 11 个更多的条目。

Is that a correct assumption?这是一个正确的假设吗?

(If no, please inform me and I will delete this answer.) (如果不是,请通知我,我将删除此答案。)

If so, I believe that there may be entries in the RESULTS table where { sample_id, machine_id } are equal, but where user_id differ.如果是这样,我相信RESULTS表中可能存在{ sample_id, machine_id }相等但user_id不同的条目。

As an example, RESULTS may contain two entries where sample_id == 1 and machine_id == 4 :例如, RESULTS可能包含两个条目,其中sample_id == 1machine_id == 4

 user_id sample_id machine_id ------------------------------- 2 1 4 1 1 4......... // other entries

When grouping these two entries by { sample_id, machine_id } , you will get one grouping containing two elements:当通过{ sample_id, machine_id }对这两个条目进行分组时,您将得到一个包含两个元素的分组:

 Key: { 1, 4 } Elements: { 2, 1, 4 }, { 1, 1, 4 }

Selecting the first element in that grouping will give you选择该分组中的第一个元素将为您提供

{ 2, 1, 4 }

, simply because { 2, 1, 4 } appeared before { 1, 1, 4 } in the table. , 仅仅是因为{ 2, 1, 4 } 4 } 在表格中出现{ 1, 1, 4 }之前。 We basically disregarded the database table entry { 1, 1, 4 } before even getting to the .Where() statement.甚至在到达.Where()语句之前,我们基本上都忽略了数据库表条目{ 1, 1, 4 }

Now, by using .Where() to get only the elements that are associated with user_id == 1 , the element { 2, 1, 4 } will be excluded , seeing as user_id == 2 .现在,通过使用.Where()仅获取与user_id == 1关联的元素,元素{ 2, 1, 4 }将被排除,视为user_id == 2


My suggestion is therefore to change the order of method calls, so that .Where() is used prior to the grouping and selection of the first group element.因此,我的建议是更改方法调用的顺序,以便在分组和选择第一个组元素之前使用.Where() A minimal example:一个最小的例子:

 var filteredResults = results.Where(r => r.user_id == 1) // filtering before grouping.GroupBy(r => new { r.machine_id, r.sample_id }).Select(r => r.First());

When doing this, the grouping will only be based on entries where userId == 1 , and therefore, no entry associated with user_id == 1 will be "lost" in the stage of selecting the first element in each grouping.这样做时,分组将仅基于userId == 1的条目,因此,在选择每个分组中的第一个元素的阶段,与user_id == 1关联的条目不会“丢失”。

This fiddle may help in displaying the difference regarding the order of method calls.这个小提琴可能有助于显示有关方法调用顺序的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM