user3328402 user3328402 - 2 months ago 5x
C# Question

Using linq fill a class from another class

I have an MVC5 application on which i am working on.

I have a situation in the app where i have to find distinct elements from a list but with a little tweak.

Let me explain the scenario.

I have a Product and Category class:-





I have multiple products so i am dealing with a list of Products:-

List<Product> listProducts = new List<Product>();

All the products can be in same category or in multiple categories. So i want to get all the distinct categories list in the category class.

To find the Distinct categories we can use linq as following:-

var listProductCategories = listProducts.Select(x => x.CategoryName).Distinct().ToList();

But this would return a List and i want List with both CategoryId and CategoryName.

Please help me with this


You can group by CategoryId and CategoryName and then project to a new Category item like:

var query = listProducts.GroupBy(r => new { r.CategoryId, r.CategoryName })
            .Select(grp => new Category
                CategoryId = grp.Key.CategoryId,
                CategoryName = grp.Key.CategoryName

You can add ToList at the end of your query if you want to get a List<Category>