Linq:在进行投影时设置属性 [英] Linq: set a property while doing a projection
问题描述
我正在做一个使用First元素的简单GroupBy,但是我想修改每个结果的一个属性.
I'm doing a simple GroupBy taking the First element but I want to modify one of the property of each result.
class M
{
public string Name {get; set;}
public int NOfPeopleWithTheSameName {get; set;}
public string P1 {get; set;}
public string P2 {get; set;}
public string P3 {get; set;}
public string P4 {get; set;}
public string P5 {get; set;}
}
List<M> myList = GetMyList();
var l2 = myList
.GroupBy(m => m.Name)
.Select(group => new M { Name = group.Key, NOfPeopleWithTheSameName = group.Count() });
这很简单,但是如果类具有许多属性(因为每个属性值都应复制到新属性),则这种方法不是最佳方法吗?我应该一一复制.
This is pretty easy, but this way is not the best if the class has many properties (since every property value should be copied to the new one)? I should copy them one by one.
我只想简单地获取元素并更改属性NOfPeopleWithTheSameName
I would like to simply take the element and change the property NOfPeopleWithTheSameName
推荐答案
您无需创建新的M
,您可以返回现有的M
,例如:
You don't need to create a new M
, you can return the existing one, for example:
var l2 = myList
.GroupBy(m => m.Name)
.Select(group =>
{
var m = group.First();
m.NOfPeopleWithTheSameName = group.Count();
return m;
});
但是,如果您只是为此目的在模型中添加属性,我建议您改用另一个类包装初始模型和计数-不要污染您的模型.例如,您可能有一个像这样的通用包装器类:
However, if you are going to add a property to your model just for this, I would suggest instead having a different class that wraps the initial model and the count - don't pollute your models. For example, you could have a generic wrapper class like this:
public class ModelCount<T>
{
public T Model { get; set; }
public int Count { get; set; }
}
现在像这样分组:
var l2 = myList
.GroupBy(m => m.Name)
.Select(group => new ModelCount<M>
{
Model = group.First(),
Count = group.Count()
});
这篇关于Linq:在进行投影时设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!