开发者

Can I do a LINQ select with .Select without havng to use a class object

开发者 https://www.devze.com 2023-04-13 07:37 出处:网络
I was wondering first of all, what is the better practice? List<Employee> _employee = new List<Employee>();

I was wondering first of all, what is the better practice?

List<Employee> _employee = new List<Employee>();
var _test = xDoc.Descendants("RID")
         .Select (x => new E开发者_运维百科mployee()
          { 


          }

Or using a Var list or something else? And how would I do this if that's a better option? This is only pulling 1-2 pieces of data out of the xDoc.


It depends on what you are going to do with the type (passing it outside of the method). Anonymous types are classes that are generated by the compiler, you just don't have to go through the effort of generating them yourself. But then again you can't pass them around to other methods either.


If you're not going to be using the object outside of the method you can create an anonymous type like so:

var _employee = xDoc.Descendants("RID")
     .Select (x => new 
      { 
        FirstName = //Something
        //Other properties here
      }).ToList(); //ToList optional

It'll still be strongly typed, but you can't return it since it you can't specify an anonymous type as a return type. (Unless you use dynamic in C#4)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号