c# - 使用LINQ c#在另一个列表中合并列表
问题描述
我有一个这样的作者课程
public class Author : IEquatable<Author>
{
public string Name { get; private set; }
public List<PublicationData> Publications { get; private set };
public Author(string name, List<PublicationData> publications)
{
Name = name;
Publications = publications;
}
public override string ToString()
{
string lines = Name + "\n";
foreach (PublicationData publication in Publications)
lines += publication.ToString() + "\n";
return lines;
}
public bool Equals(Author other)
{
return Name.Equals(other.Name);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
我有这样的出版课
public class PublicationData : IEquatable<PublicationData>
{
public string Code { get; set; }
public int Amount { get; set; }
public int Subscription_Length { get; set; }
public PublicationData(string name, int amount, int subscription_Length)
{
Code = name;
Amount = amount;
Subscription_Length = subscription_Length;
}
public override string ToString()
{
return String.Format($"{Code}, {Amount}, {Subscription_Length}");
}
public bool Equals(PublicationData other)
{
return Code.Equals(other.Code);
}
public override int GetHashCode()
{
return Code.GetHashCode();
}
}
然后我有一个看起来像这样的作者列表:
作者A - 出版物A
作者B - 出版物B
作者B - 出版物C
我想得到这样的东西作为一个新的对象:
作者A - 出版物A
作者B - 出版物B - 出版物C
我假设代码应该是这样的:
var filtered = authors.Select(nn => new Author
(
nn.Name,
// merge publication lists
)).Distinct()
.ToList();
我只是不知道我该怎么做。任何人都可以提出一些建议吗?
解决方案
看来您正在寻找GroupBy
方法:
authors
.GroupBy(a => a.Name)
.Select(g => new Author(
g.Key,
g.SelectMany(ga => ga.Publications).ToList()))
推荐阅读
- php - 你好,我用php curl做了一个研究,响应没有我想要的响应。问题出在哪里?
- django - IntegrityError(错误)而不是 ValidationError(正确)
- python - 将字符串拆分为字母组,忽略空格
- python - 我想使用 discord.py 发出命令,当有人对消息做出反应时触发
- go - 我可以使用 go 命令行工具设置 GOPATH 吗?
- python - 通过信号量进行线程同步后无法同时运行三个线程
- apache-spark - 从 Spark 结构化流作业写入时的增量表版本控制
- java - Java File Watcher 无法识别文件更改
- sql - 如何向所有在餐厅举行多次会议的客户展示
- php - 从数组打印 Html 表格