gpt4 book ai didi

c# - 如何在 LINQ 中使用 GroupBy 查找丢失的项目?

转载 作者:行者123 更新时间:2023-12-02 14:10:18 24 4
gpt4 key购买 nike

我有一个这样的场景,我收集了这些项目

public class Submission {
public DateTime ProcessedDate { get; set; }
public string UserName { get; set; }
}

我需要检查用户名集合,例如:

string[] names = new string{"Paul", "John", "George", "Ringo"};

我想找出哪些日期缺少提交(并非所有这些用户名都有条目的日期)。所以想象一下测试数据:

var submissions = new List<Submission>();
submissions.Add(new Submission() { ProcessedDate = new DateTime(2018, 1, 1), UserName = "Paul" });
submissions.Add(new Submission() { ProcessedDate = new DateTime(2018, 1, 1), UserName = "John" });
submissions.Add(new Submission() { ProcessedDate = new DateTime(2018, 1, 1), UserName = "George" });
submissions.Add(new Submission() { ProcessedDate = new DateTime(2018, 1, 1), UserName = "Ringo" });
submissions.Add(new Submission() { ProcessedDate = new DateTime(2018, 1, 2), UserName = "Paul" });
submissions.Add(new Submission() { ProcessedDate = new DateTime(2018, 1, 2), UserName = "John" });
submissions.Add(new Submission() { ProcessedDate = new DateTime(2018, 1, 3), UserName = "George" });
submissions.Add(new Submission() { ProcessedDate = new DateTime(2018, 1, 3), UserName = "Ringo" });

1/1 已提交所有用户名,但 1/2 和 1/3 均缺少条目,如何返回缺少的条目的集合(缺少日期和该日期缺少的用户)?

2018-01-02 - 乔治、林戈

2018-01-03 - 保罗,约翰

最佳答案

如果您只需要日期,请使用以下查询:

var result = submissions.GroupBy(o => o.ProcessedDate)
.Where(o => names.Any(x => !o.Any(s => s.UserName == x)))
.Select(o => o.Key)
.ToList();

如果您需要 Submission 对象列表,请使用以下对象:

var resultWithSubmissions = submissions.GroupBy(o => o.ProcessedDate)
.Where(o => names.Any(x => !o.Any(s => s.UserName == x)))
.SelectMany(o => o)
.ToList();

如果您需要每个日期缺失的用户名列表,请使用以下查询:

var resultWithMissingNames = submissions.GroupBy(o => o.ProcessedDate)
.Where(o => names.Any(x => !o.Any(s => s.UserName == x)))
.Select(o => new { ProcessedDate = o.Key, MissingNames = string.Join(",", names.Except(o.Select(x => x.UserName)))})
.ToList();

关于c# - 如何在 LINQ 中使用 GroupBy 查找丢失的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49451887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com