Reputation: 5011
I have a list GroupMembershipValidList that contains objects of type GroupMembershipUploadInput.
This GroupMembershipUploadInput class definition looks like
public class GroupMembershipUploadInput
{
public string chpt_cd { get; set; }}
public string cnst_last_nm { get; set; }
public string appl_src_cd { get; set; }
}
I have simplified the definition for the sake of simplicity.
Now I have another list _validChapterCodes (public List<ChapterCodeValidationOutput> _validChapterCodes { get; set; }
)
that contains objects of type
public class ChapterCodeValidationOutput
{
public string chpt_cd { get; set; }
public string appl_src_cd { get; set; }
}
So, What I want to do is .. if the chpt_cd from list A matches list B , then populate the appl_src_cd names from list B to list A objects.
How would I do it in LINQ ?
I tried ...
gmvo.GroupMembershipValidList.GroupMembershipUploadInputList.Where(x => gmvo._validChapterCodes.Contains(x.chpt_cd)).Select(y => y.appl_src_cd);
But I know I am not doing it properly .
Upvotes: 0
Views: 489
Reputation: 218702
You can use a LINQ expression.
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();
Assuming a is a collection of GroupMembershipUploadInput
and b is a collection of ChapterCodeValidationOutput
Upvotes: 1
Reputation: 43876
LINQ has a functional approach, meaning it's for getting values out of a set of existing values, not for manipulating existing values.
So you can't avoid at least one foreach
here. I'd do it like this:
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()
returns the first element from your input list with a matching chpt_cd
or null
if there is no matching element.
EDIT: From your question I'm not sure if you wanted it that way or the other way around (what is list A and list B?). So for completeness the other way:
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;
}
Upvotes: 1