使用linq迭代两个差异对象数组

roejwanj  于 2023-02-27  发布在  其他
关注(0)|答案(2)|浏览(119)

我有两个不同对象的数组,但其中一个值是使它们之间建立联系的值,就像它是一个外键一样。我想将一个对象的值添加到另一个对象中,但要使用Linq或以比下面更简洁的方式:

public static List<GroupSimpleModel> ToModelWithMark(List<GroupSimpleEntity> groups, List<GroupMarkedEntity> markGroups)
        {
            List<GroupSimpleModel> groupSimpleModelsMarked = new List<GroupSimpleModel>();
            foreach (var group in groups)
            {
                GroupSimpleModel groupSimpleModelMarked = new GroupSimpleModel()
                {
                    Code = group.Code,
                    Id = group.Id,
                    ParentId = group.ParentId,
                    ProfileId = group.ProfileId,
                    MarkedTypeCodes = new List<string>()
                    
                };
                foreach (var mark in markGroups)
                {
                    if (mark.GroupId == group.Id)
                    {
                        groupSimpleModelMarked.MarkedTypeCodes.Add(mark.MarkedTypeCode);
                    }
                }
                groupSimpleModelsMarked.Add(groupSimpleModelMarked);
            }
            return groupSimpleModelsMarked;
        }

谢谢你的建议。

zfycwa2u

zfycwa2u1#

接受的答案是次优的,因为它重复执行线性搜索。GroupJoin()可以为您执行该搜索,并且只执行一次:

var result = groups.GroupJoin(
    markGroups,
    g => g.Id,
    gm => gm.GroupId,
    (g, gms) => new GroupSimpleModel {
        Code = g.Code,
        Id = g.Id,
        ParentId = g.ParentId,
        ProfileId = g.ProfileId,
        MarkedTypeCodes = gms.Select(gm => gm.MarkedTypeCode).ToList()
    })
ujv3wf0j

ujv3wf0j2#

只需从您的代码翻译:

groups.Select(group => new GroupSimpleModel()
       {
           Code = group.Code,
           Id = group.Id,
           ParentId = group.ParentId,
           ProfileId = group.ProfileId,
           MarkedTypeCodes = markGroups.Where(mark => mark.GroupId == group.Id)
                                       .Select(mark => mark.MarkedTypeCode)
                                       .ToList();
       })
      .ToList();

相关问题