linq select 实体额外赋值成实体(未测试效率)

方法:

        /// <summary>
        /// 实体类复制
        /// </summary>
        /// <param name="objold"></param>
        public static dynamic EntityCopy(object objone, object objtow)
        {
            dynamic objnew = new System.Dynamic.ExpandoObject();
            Type myType = objone.GetType();
            Type myType2 = objtow.GetType();
            PropertyInfo currobj = null;

            PropertyInfo[] myProperties = myType.GetProperties();
            for (int i = 0; i < myProperties.Length; i++)
            {
                currobj = objone.GetType().GetProperties()[i];
                var ss = currobj.GetValue(objone, null);
                //currobj.SetValue(objnew, currobj.GetValue(objold, null), null);
                (objnew as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>).Add(new KeyValuePair<string, object>(currobj.Name, ss));
            }

            myProperties = myType2.GetProperties();
            for (int i = 0; i < myProperties.Length; i++)
            {
                currobj = objtow.GetType().GetProperties()[i];
                var ss = currobj.GetValue(objtow, null);
                //currobj.SetValue(objnew, currobj.GetValue(objold, null), null);
                (objnew as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>).Add(new KeyValuePair<string, object>(currobj.Name, ss));
            }
            return objnew;
        }

使用:

//数据集关联
                var data = (from l in lists
                            join u in UnitWork.Find<Base_User>(null) on l.Creater equals u.Id into userrooms
                            from u in userrooms.DefaultIfEmpty()
                            join h in UnitWork.Find<Hotel>(null) on l.H_Id equals h.Id into hotel
                            from h in hotel.DefaultIfEmpty()
                            join t in UnitWork.Find<Base_MessageType>(null) on l.BM_Id equals t.Id into msgtype
                            from t in msgtype.DefaultIfEmpty()
                            select ObjectHelper.EntityCopy(l, new
                            {
                                BM_Name = t == null ? null : t.Name,
                                H_Name = h == null ? null : h.Name,
                                CreaterName = u == null ? null : u.Name
                            })
                            ).ToList();

结果:

[
    {
      "Contents": "1",
      "BM_Id": 1,
      "SourceId": 1,
      "ReceiveId": 1,
      "H_Id": 3,
      "Status": 1,
      "Creater": 1,
      "CreateTime": "2020-11-03T00:00:00",
      "Id": 3,
      "BM_Name": null,
      "H_Name": "测试酒店",
      "CreaterName": "管理"
    }
}
原文地址:https://www.cnblogs.com/ruiyuan/p/13927205.html