LINQ从一个集合查询以填充另一个集合

时间:2016-06-21 14:40:21

标签: c# linq

我有一个列表 GroupMembershipValidList ,其中包含GroupMembershipUploadInput类型的对象。

此GroupMembershipUploadInput类定义类似于

   public class GroupMembershipUploadInput
    {
        public string chpt_cd { get; set; }}
        public string cnst_last_nm { get; set; }
        public string appl_src_cd { get; set; }

    }

为简单起见,我简化了定义。

现在我有另一个列表 _validChapterCodes public List<ChapterCodeValidationOutput> _validChapterCodes { get; set; }

包含

类型的对象
public class ChapterCodeValidationOutput
{
    public string chpt_cd { get; set; }
    public string appl_src_cd { get; set; }
}

所以,我想要做的是..如果列表A中的chpt_cd与列表B匹配,则填充列表B中的appl_src_cd名称以列出A对象。

我如何在LINQ中执行此操作?

我试过......

gmvo.GroupMembershipValidList.GroupMembershipUploadInputList.Where(x => gmvo._validChapterCodes.Contains(x.chpt_cd)).Select(y => y.appl_src_cd);

但我知道我做得不好。

2 个答案:

答案 0 :(得分:1)

LINQ有功能方法,这意味着它是从一组现有值中获取值,而不是操纵现有值。

所以你不能在这里避免至少一个foreach。我会这样做:

foreach(var chapter in _validChapterCodes)
{
    ChapterCodeValidationOutput output = GroupMembershipValidList.FirstOrDefault(e =>
        e.chpt_cd == chapter.chpt_cd);
    if (input != null) chapter.appl_src_cd = input.appl_src_cd;
}
如果没有匹配的元素,

FirstOrDefault()会返回输入列表中第一个匹配chpt_cdnull的元素。

编辑:从你的问题我不确定你是否想要那样或反过来(什么是列表A 列表B ?)。所以为了完整性,另一种方式:

foreach(var input in GroupMembershipValidList)
{
    var chapter = _validChapterCodes.FirstOrDefault(e =>
        e.chpt_cd == input.chpt_cd);
    if (chapter != null) input.appl_src_cd = chapter.appl_src_cd;
}

答案 1 :(得分:1)

您可以使用LINQ表达式。

var a = new List<GroupMembershipUploadInput>
{
    new GroupMembershipUploadInput() {chpt_cd = "A" },
    new GroupMembershipUploadInput() {chpt_cd = "A2"" },
    new GroupMembershipUploadInput() {chpt_cd = "A3" }
};

var b = new List<ChapterCodeValidationOutput>
{
    new ChapterCodeValidationOutput() {chpt_cd = "A", appl_src_cd = "ACode"},
    new ChapterCodeValidationOutput() {chpt_cd = "C2", appl_src_cd = "C22"},
    new ChapterCodeValidationOutput() {chpt_cd = "A3", appl_src_cd = "A33"}
};


var result = a.Select(s => new GroupMembershipUploadInput
{
    chpt_cd = s.chpt_cd,
    appl_src_cd = b.Any(u => u.chpt_cd == s.chpt_cd) ?
                          b.First(v => v.chpt_cd == s.chpt_cd).appl_src_cd:string.Empty
}).ToList();

假设a是GroupMembershipUploadInput的集合,b是ChapterCodeValidationOutput的集合

相关问题