简体   繁体   English

IEnumerable中的地方ID <int> 在单个LINQ查询中

[英]Place IDs in IEnumerable<int> within single LINQ query

I've got a dataset of this format: 我有这种格式的数据集:

ID   Make        Model
==   =========   =========
1    Ford        Fusion
2    Ford        Fusion
3    Chevy       Malibu

I want the result to be: 我希望结果是:

Make      Model      IDs
========  =========  ===
Ford      Fusion     IEnumerable<int> {1,2}
Chevy     Malibu     IEnumerable<int> {3}

I'm implementing multi-line edits in a grid so I need to save the IDs of each line while displaying the distinct properties to edit. 我正在网格中实现多行编辑,因此需要在显示不同属性进行编辑的同时保存每行的ID。 Once the editing is done then I will have the IDs to update. 编辑完成后,我将有ID要更新。

I'm wondering if there is a way to collate these IDs with a single LINQ query. 我想知道是否有一种方法可以通过单个LINQ查询来整理这些ID。 Currently I've been successful but with two queries. 目前,我已经成功了,但有两个疑问。

A simple group by should work: 一个简单的分组依据应该起作用:

var query=from c in cars
          group c.Id by new {c.Make,c.Model} into g
          select new {g.Key.Make, g.Key.Model, Ids=g.ToList() };

You can try something like this: 您可以尝试如下操作:

var results = context.Cars
                     .GroupBy(c => new { c.Make, c.Model })
                     .Select(g => new
                     {
                         Make = g.Key.Make,
                         Model = g.Key.Model,
                         IDs = g.Select(c => c.ID)
                     });

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

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