我想在分组结果中使用参数“ o”(源对象),如下所示:
return (from o in objects
group o by MySpecialConverter(o) into g
select new Group
{
Key = g.Key,
Items = g.ToList(),
Source = o, // Error: The name 'o' does not exist in the current context.
...
}).ToList();
但是,我无法在新组中访问“ o”。
答案 0 :(得分:1)
在group语句中使用分组元素,而不是使用used元素。
return (from o in objects
group o by MySpecialConverter(o) into g
select new Group // Create Group class with the data types and object bellow
{
Key = g.Key,
Items = g.ToList(),
Source = g // used the grouped element here for selection
}).ToList();
或者,如果要获取任意数量的元素,第一个元素或最后一个元素,则可以使用let关键字。
return (from o in objects
group o by MySpecialConverter(o) into g
let oLocal = g.FirstOrDefault()
select new Group // Create Group class with the data types and object bellow
{
Key = g.Key,
Items = g.ToList(),
Source = oLocal // used the grouped element here for selection
}).ToList();