Both snippets of code work, however, I'm wondering which one is a better(if any). Is there a real difference? The part of the code I'm referring to is in the LINQ. Any insight would be appreciated.
select new Product {...
First Snippet:
public static IEnumerable<Product> GetProducts(IEnumerable<Product> products)
{
var query = from p in products
select new Product
{
Category = p.Category,
Id = p.Id,
CategoryId = p.CategoryId,
Name = p.Name
};
return query;
}
class Product
{
public int Id { get; set; }
public String Name { get; set; }
public Category Category { get; set; }
public int CategoryId { get; set; }
}
class Category
{
public int Id { get; set; }
public String CategoryName { get; set; }
}
Second Snippet:
public static IEnumerable<Product> GetProducts(IEnumerable<Product> products)
{
var query = from p in products
select p;
return query;
}
class Product
{
public int Id { get; set; }
public String Name { get; set; }
public Category Category { get; set; }
public int CategoryId { get; set; }
}
class Category
{
public int Id { get; set; }
public String CategoryName { get; set; }
}
new Product {syntax reminds the OP of anonymous classes, but of course those are not being used here either. Rather, this construct is called an object initializer.