2016-06-21 144 views
0

我有一个列表GroupMembershipValidList包含GroupMembershipUploadInput类型的对象。LINQ查询从一个集合到另一个集合

这GroupMembershipUploadInput类定义看起来像

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

    } 

我已经简化了简单起见定义。

现在我有另一个列表_validChapterCodespublic 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); 

但我知道我没有做正确。

+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如果没有匹配的元素。


编辑:从你的问题我不知道,如果你希望它这样或周围的其他方式(是什么列表一个名单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; 
} 
+0

好的,但如果对于列表中的第二个对象,chpt_cd与第一个对象相同,对于第二个对象,appl_src_cd将作为null。我怎样才能避免它? – StrugglingCoder

+0

不,如果它是相同的'chpt_cd',它会返回相同的元素。你没有在你的问题中指定这些'chpt_cd'是否是唯一的,或者你想要如何填充'appl_src_cd'。 –

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(); 

假设是GroupMembershipUploadInput和B的集合是ChapterCodeValidationOutput

+0

它会在这里填充相同的集合吗? – StrugglingCoder

+0

是的。结果将是所有来自a的项目的新列表,但appl_src_cd属性填充来自集合b的值以用于匹配项目。 – Shyju

+1

这就是要点,这会创建一个_new_列表,但不会像请求的问题那样填充_existing_列表。 –

相关问题