Get subllist from a list in C# LINQ by removing few columns

Azaz Ahmad Tapadar 1 Reputation point

I have a list with few records. Now I want to create a new list from this existing list by removing few unwanted columns. Please guide me how to the same using LINQ C#.

Entity Framework 6.0
Entity Framework 6.0
A Microsoft open-source object-database mapper for .NET.
266 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,432 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 34,581 Reputation points

    One example, create a class that represents only properties you need.

    public static async Task<CustomerItem> Example(int companyId)  
        await using var context = new Context();  
        return await context  
            .Select(c => new CustomerItem()  
                CompanyName = c.CompanyName,  
                ContactId = c.ContactId,  
                CustomerIdentifier = c.CustomerIdentifier  
            }).FirstOrDefaultAsync(x => x.CustomerIdentifier == companyId);  


    Or perhaps using a projection where in the following example, data comes from Vendor model and returns a sub-set of type VendorListItem.

    public class VendorListItem  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public int NumberOfFruits { get; set; }  
        public static Expression<Func<Vendor, VendorListItem>> Projection  
                return x => new VendorListItem()  
                    Id = x.Id,  
                    Name = x.Name,  
                    NumberOfFruits = x.Fruits.Count()  
    0 comments No comments