首页 > 解决方案 > 使用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();

我只是不知道我该怎么做。任何人都可以提出一些建议吗?

标签: c#listvisual-studiolinq

解决方案


看来您正在寻找GroupBy方法:

authors
    .GroupBy(a => a.Name)
    .Select(g => new Author(
        g.Key,
        g.SelectMany(ga => ga.Publications).ToList()))

推荐阅读