Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a property of an object from another list using LINQ

Tags:

c#

linq

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
like image 968
dogeter Avatar asked Dec 27 '22 16:12

dogeter


1 Answers

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;
                });
like image 115
Manek Avatar answered May 10 '23 09:05

Manek