LINQ - Add property to results

前端 未结 5 1090
日久生厌
日久生厌 2020-12-18 23:15

Is there a way to add a property to the objects of a Linq query result other than the following?

var query = from x in db.Courses
                select new
         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-18 23:52

    If you are looking to dynamically add a property to an object this could be a solution.

    This is what has worked for me, I also had a concern and it was what happened with those domain objects that had many properties, the maintainability for any changes in the object was absurd, I managed to build an implementation with LINQ - ExpandObject - Reflection, which helped to keep my object dynamic and only add the additional properties that my view logic required.

    var expandedModel = db.Courses.Select(x =>
                        {
                            dynamic expandObject = new ExpandoObject();
                            expandObject.NewProperty= $"PropertyValue";
                            foreach (var property in x.GetType().GetProperties())
                            {
                                ((IDictionary)expandObject).Add(property.Name, property.GetValue(x));
                            }
                            return expandObject;
                        }).ToList();
    

提交回复
热议问题