需要在列表中查找订单
希望得到两个项目的列表
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; }
}
}
答案 0 :(得分:2)
请先尝试一下
unfilteredOrders.GroupBy(order => order.Title)
.Select(orderGroup =>
orderGroup.OrderByDescending(o => o.Description.Length)
.First())
.ToList();