.net C# LINQ从列表中选择所有属性并添加一个附加属性,而无需创建新的强类型类

xfb7svmp  于 2023-08-08  发布在  .NET
关注(0)|答案(3)|浏览(113)
var people = new[]
        {
           new {Id = 6000, Name = "Jennifer", Age = 21}, 
           new {Id = 6001, Name = "Alton", Age = 15},
           new {Id = 6003, Name = "Milford", Age = 23}
        };

字符串
想要的结果:

{ Id = 6000, Name = Jennifer, Age = 21 , Is Minor = false }
{ Id = 6001, Name = Alton, Age = 15, Is Minor = true }
{ Id = 6003, Name = Milford, Age = 23, Is Minor = false }


添加附加属性是Minor,而不创建返回结果的新类``

odopli94

odopli941#

使用LINQ中的Select方法,如下所示:

var people = new[]
{
    new { Id = 6000, Name = "Jennifer", Age = 21 },
    new { Id = 6001, Name = "Alton", Age = 15 },
    new { Id = 6003, Name = "Milford", Age = 23 }
};

var peopleWithIsMinor = people.Select(person => new
{
    person.Id,
    person.Name,
    person.Age,
    IsMinor = person.Age < 18
});

字符串

bz4sfanl

bz4sfanl2#

如果你不想创建一个新的强类型类,那么使用一个匿名类(就像你的例子一样)可能是你最好的选择。

var result = people.Select(person => new
{
  person.Id,
  person.Name,
  person.Age,
  IsMinor = GetIsMinor(person)
});

字符串
我假设您可以根据现有属性确定附加属性的值。

y1aodyip

y1aodyip3#

这就是你要找的吗?

var result = people.Select(item => new
{
     Id = item.Id,
     Name = item.Name,
     Age = item.Age,
     IsMinor = item.Age < 18
}).ToList();

字符串

相关问题