首页 > 解决方案 > 获取具有最长描述和不同标题的项目c#

问题描述

需要在列表中查找订单

想要的结果是两个项目的列表

new Order
{
    Title = "This is a title",
    Description ="This is the longest description with a title This is a title"
},
new Order
{
    Title = "Another title",
    Description =
        "Another description and is the longest description with title Another title"
}

如上所述,我的尝试没有返回想要的结果

using System;
using System.Collections.Generic;
using System.Linq;
using MoreLinq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main()
        {
            var unfilteredOrders = new List<Order>
            {
                new Order {Title = "This is a title", 
                Description = "This is a description"},
                new Order {Title = "This is a title", 
                Description = "this is another description"},
                new Order
                {
                    Title       = "This is a title",
                    Description = "This is the longest description with a title This is a title"
                },
                new Order {Title = "This is a title", 
                Description = "Test this is a title"},

                new Order {Title = "Another title", 
                Description = "another description "},

                new Order {Title = "Another title", 
                Description = "another description belonging to another title"},

                new Order
                {
                    Title = "Another title",
                    Description =
                        "Another description and is the longest description with title Another title"
                }
            };

            //need to return a List<Order>
            var orders =
                //unfilteredOrders.DistinctBy(order => order.Title)
                unfilteredOrders.GroupBy(order => order.Title)
                         .Select(orderGroup => new
                         {
                             Title = orderGroup.Key,
                             Description =
                                 orderGroup.MaxBy(x => x.Description), //uses morelinq MaxBy  (open to suggestions)
                         }).ToList();

            foreach (var order in orders)
            {
                Console.WriteLine(order.Title);
                Console.WriteLine(order.Description);
                Console.WriteLine("--------");
            }

            Console.Read();
        }
    }

    public class Order
    {
        public string Title       { get; set; }
        public string Description { get; set; }
    }
}

标签: c#linq

解决方案


正是我首先要尝试的:

 unfilteredOrders.GroupBy(order => order.Title)
          .Select(orderGroup => 
               orderGroup.OrderByDescending(o => o.Description.Length)
              .First())
          .ToList();

推荐阅读