Home > Enterprise >  Can we remove the repeating string elements here? Linq C#
Can we remove the repeating string elements here? Linq C#

Time:10-10

enter image description here

 static IEnumerable<MaxDiscountOwner> Task(IEnumerable<Supplier> supplierList,
            IEnumerable<SupplierDiscount> supplierDiscountList)
        {

            var b = supplierDiscountList.OrderBy(x => x.ShopName).ThenBy(a => a.Discount).
            Select(x => new MaxDiscountOwner
            {
                ShopName = x.ShopName,
                Discount = x.Discount,
                Owner = supplierList.Where(a => a.Id == x.SupplierId).FirstOrDefault()
            }).OrderByDescending(g => g.Discount);

            return b;
            
        }

I want to remove the repeated MaxDiscountOwner elements after OrderByDescending(g => g.Discount) by string shop, how can I do it and can I do it at all?

supplierDiscountList is array new SupplierDiscount { Discount = 5.0, ShopName = "shop1", SupplierId = 1 }, similar objects.

MaxDiscountOwner[] expected = new[]
new MaxDiscountOwner
                    {
                        Discount = 5.0, ShopName = "shop1",
                        Owner = new Supplier{Adress = "adress 1", Id = 1, YearOfBirth = 2000}
                    },
 new MaxDiscountOwner
                    {
                        Discount = 34.0, ShopName = "shop2",
                        Owner = new Supplier{Adress = "adress 2", Id = 2, YearOfBirth = 1961}
                    },
and until we run out of stores

supplierList its array of "Supplier{Adress = "adress 1", Id = 1, YearOfBirth = 2000}, .."

CodePudding user response:

I hope I got it right

 static IEnumerable<MaxDiscountOwner> Task(IEnumerable<Supplier> supplierList,
        IEnumerable<SupplierDiscount> supplierDiscountList)
    {

        return  supplierDiscountList.OrderBy(x => x.ShopName).ThenBy(a => a.Discount)
                                    .Select(x => new MaxDiscountOwner
                                    {
                                        ShopName = x.ShopName,
                                        Discount = x.Discount,
                                        Owner = supplierList.Where(a => a.Id == x.SupplierId).FirstOrDefault()
                                    })
                                    .OrderByDescending(g => g.Discount)
                                    .GroupBy(x => (x.ShopName ?? "").Trim()) // maybe add ToLower() yet
                                    .Select(x => x.OrderByDescending(g => g.Discount).First());           

        
    }
  • Related