如何在 LINQ 中获取和使用分组源?
How to get and use source of grouping in LINQ?
我想在分组结果中使用参数 "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"。
使用分组的元素而不是在组语句中使用已使用的元素。
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();
我想在分组结果中使用参数 "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"。
使用分组的元素而不是在组语句中使用已使用的元素。
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();