Home > Software engineering >  Merge to various type List in to new List Type
Merge to various type List in to new List Type

Time:08-13

I have 2 list

IEnumerable<int> Ids, IEnumerable<Guid> GuidIds

for sample data

IEnumerable<int> ids1 = new List<int>() { 1, 2, 4 };
IEnumerable<Guid> guidIds = new List<Guid>() { new Guid("F44D7A64-8BDE-41E1-810F-B24377AD7F94"), new Guid("F44D7A64-8BDE-41E1-810F-B24377AD7F96"), new Guid("F44D7A64-8BDE-41E1-810F-B24377AD7F97") };

and a class

public class ClassEnd
    {
        public int Id { get; set; }

        public Guid GuidId { get; set; }
    }
    

I want to merge into this by Linq query

IEnumerable<ClassEnd> mergeList = new List<ClassEnd>()
            {
                new ClassEnd() { Id = 1, CompanyId = new Guid("F44D7A64-8BDE-41E1-810F-B24377AD7F94") },
                new ClassEnd() { Id = 2, CompanyId = new Guid("F44D7A64-8BDE-41E1-810F-B24377AD7F96") },
                new ClassEnd() { Id = 3, CompanyId = new Guid("F44D7A64-8BDE-41E1-810F-B24377AD7F97") }
            };

Could you please help me with how to merge like the above "mergeList" by using Linq?

CodePudding user response:

If lists are of the same size - it can be easily achieved with Enumerable.Zip:

var classEnds = ids1
    .Zip(guidIds, (i, guid) => new ClassEnd
    {
        Id = i,
        GuidId = guid
    })
    .ToList();
  • Related