I have 2 lists of objects. One has values, the other has names and values. I want to look up the values in the other list and write the result to pref.Name. I know I can do this with a foreach, but I assume there's a good way to do it in LINQ. Ideas?
public class Preference
{
public string Category { get; set; }
public string Name { get; set; }
public string ItemValue { get; set; }
public int SortOrder { get; set; }
}
public class SAPReadOnlyItem
{
public string Category { get; set; }
public string Name { get; set; }
public string ItemValue { get; set; }
}
List<Preference> preferences = getExistingUserPreferences(UserID, ddlCategory.SelectedValue); //this list is just keys
List<SAPReadOnlyItem> sapReadOnlyItems = getSAPReadOnlyItems(ddlCategory.SelectedValue); //this list is names and keys
//i want to look up the name from sapReadOnly using the ID from preferences and write it into preferences[n].Name
//this works, but I want to write it into preferences[n].Name
var foobar = (from sap in sapReadOnlyItems
join pref in preferences
on sap.ItemValue equals pref.ItemValue
select new { asdf = sap.Name }).FirstOrDefault(); //instead of "select new" I want to write it into preferences[n].Name
I suggest using a Lambda foreach
preferences.ForEach(preference =>
{
var sap = sapReadOnlyItems.FirstOrDefault(s => s.ItemValue = preference.ItemValue);
preference.Name = (sap != null) ? sap.Name : string.Empty;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With