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

Azaz Ahmad Tapadar 1 Reputation point
2022-10-24T08:29:14.253+00:00

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#.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,860 questions
C#
C#
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.
10,933 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,421 Reputation points
    2022-10-24T11:49:08.313+00:00

    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  
            .Customers  
            .Select(c => new CustomerItem()  
            {  
                CompanyName = c.CompanyName,  
                ContactId = c.ContactId,  
                CustomerIdentifier = c.CustomerIdentifier  
                  
            }).FirstOrDefaultAsync(x => x.CustomerIdentifier == companyId);  
    }  
    

    253470-f1.png

    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  
        {  
            get  
            {  
                return x => new VendorListItem()  
                {  
                    Id = x.Id,  
                    Name = x.Name,  
                    NumberOfFruits = x.Fruits.Count()  
                };  
            }  
        }  
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.