Can I do a LINQ select with .Select without havng to use a class object
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)
精彩评论