none
如何在Linq语句中执行代码? RRS feed

  • 常规讨论

  • 如何在Linq语句中执行代码?

    Linq一般用于查询集合数据,不方便在Linq语句内执行相关代码。

    按如下示例,可直接在Linq语句中执行代码。

    如有更好办法,请指正。

            /// <summary>
            /// 调用创建数据表结构。
            /// </summary>
            private void CreateDataTableStructure_Call()
            {
                var Fields = "Name,String|Gender,String|Photo,Byte[]|Notes,String";
                var Data = CreateDataTableStructure(Fields);
            }

            /// <summary>
            /// 创建数据表结构。
            /// Fields格式示例: "Name,String|Gender,String|Photo,Byte[]|Notes,String"
            /// </summary>
            /// <param name="Fields"></param>
            /// <returns></returns>
            private DataTable CreateDataTableStructure(string Fields)
            {
                var Rlt = new DataTable();
                var Lnq = from X in Fields.Split(new string[] { "|" }, StringSplitOptions.None)
                          let XField = X.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                          let XName = (XField.Length > 0 ? XField[0] : "").Trim()
                          where XName != ""
                          let XTypeFunc = new Func<Type>(() =>
                          {
                              var XStr = (XField.Length >= 1 ? XField[1] : "").Trim();
                              if (!XStr.ToUpper().StartsWith("System.".ToUpper())) { XStr = "System." + XStr; }
                              var XRlt = Type.GetType(XStr, false, true);
                              XRlt = XRlt == null ? typeof(string) : XRlt;
                              return XRlt;
                          })
                          let XType = XTypeFunc()
                          let XColumn = new DataColumn(XName, XType)
                          let XAddColumnAction = new Func<bool>(() => { Rlt.Columns.Add(XColumn); return true; })
                          let XCallAddColumnAction = XAddColumnAction()
                          select false;
                var ExecuteLnq = Lnq.Count();
                return Rlt;
            }

    2012年10月31日 2:09

全部回复