c# - 获取具有最长描述和不同标题的项目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; }
}
}
解决方案
正是我首先要尝试的:
unfilteredOrders.GroupBy(order => order.Title)
.Select(orderGroup =>
orderGroup.OrderByDescending(o => o.Description.Length)
.First())
.ToList();
推荐阅读
- typescript - 无法通过条件输入访问属性
- flutter - Flutter 中的安全性:google_maps_flutter 需要 API 密钥,但如何安全地提供它们?
- apache-spark - Spark 最大查询大小
- spring-boot - spring-kafka 消费者批处理错误处理与 spring boot 版本 2.3.7
- php - 检测过期 Webhook 的 PHP 函数
- python - 按属性拆分
- java - 比较两个相同的 java 字节数组返回 false
- android - 如何在firebase中使用更新?
- sql - 在 Spark 3.0 中,如何使用 sql 从特定列中删除重复项?据我了解,不支持 distinct
- c# - 比较同一列表中对象的值