设置对象的属性

Eme*_*rop 1 c# linq

我想通过LINQ查询获取一个对象列表.问题是我需要设置该对象的属性,但这些属性未在其构造函数中设置.

categories.Select(c => new { c.catId, c.catName, c.catParent })
          .Where(c => c.catParent == id)
          .AsEnumerable()
          .Select(c => new CatInfoType())
          .ToList();
Run Code Online (Sandbox Code Playgroud)

例如,在Select中我需要设置CatInfoType实例的公共属性,如Id,Name等.

Bru*_*oLM 6

您可以使用对象初始化程序

new CatInfoType
{
    PropertyX = 1,
    PropertyY = 2,
};
Run Code Online (Sandbox Code Playgroud)

要么

.Select(c =>
{
    var r = new CatInfoType();
    r.X = 1;
    r.Y = 2;
    return r;
})
Run Code Online (Sandbox Code Playgroud)