Kgn-web
Kgn-web

Reputation: 7555

how do I filter properties from an entity using select() of Linq?

Below is my DTO.

public class Product
{
    public int PId { get; set; }
    public decimal Price { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    //& so on
}

Method to get the list of products.

 public void GetProducts()
    {
        // below dal method returns collection of products. 
        // I am in need to select only few properties of the Product Entitiy
        var product = dalLayer.GetProductsList().Select(x => x.PId, y => y.Name)

    }

I cannot filter the properties in DAL layer because this method is called from multiple places & different call require different properties.

I tried below stuff.

  var products = dalLayer.GetProductsList().Select(
                    (x, y) => new
                    {
                        x.Id,
                        y.Name
                    });

But this also throwing compile time error

so How do I filter properties from product entity using select()??

Thanks.

Upvotes: 1

Views: 93

Answers (2)

Pedro Perez
Pedro Perez

Reputation: 932

You could use tuples.

Before C# 7 tuples.

var products = dalLayer.GetProductsList().Select(x => Tuple.Create(x.PId, x.Name)); 

foreach(var p in products)
{
    Console.WriteLine(p.Item1);
    Console.WriteLine(p.Item2);
}

Using C# 7. C# 7 new Features

var products = dalLayer.GetProductsList().Select(x => Tuple.Create(x.PId, x.Name));

foreach(var (PId, Name) in products)
{
    Console.WriteLine(PId);
    Console.WriteLine(Name);
}

Upvotes: 0

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13765

try the following

 var products = dalLayer.GetProductsList().Select(
                    pr => new
                    {
                        Id =pr.Id,
                        EndDate =pr.EndDate,
                        StartDate=pr.Startdate,
                    });

but note that you are creating an anonymous object

Update

Or if you don't want an anonymous object just create a view

 public class ProductViewDto
 { 
    public int  Id{get;set;}
    public DateTime EndDate {get;set;}
    public DateTime  StartDate{get;set;} 
 }

 var products = dalLayer.GetProductsList().Select(
                        pr => new ProductViewDto
                        {
                            Id =pr.Id,
                            EndDate =pr.EndDate,
                            StartDate=pr.Startdate,
                        });

Upvotes: 1

Related Questions