2012-10-16 90 views
3

我有2個對象列表。一個有價值觀,另一個有名字和價值觀。我想查看其他列表中的值並將結果寫入pref.Name。我知道我可以用foreach做到這一點,但我認爲在LINQ中有很好的方法。想法?如何使用LINQ從另一個列表填充對象的屬性

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 

回答

0

我想出了這一點:

foreach (Preference pref in preferences) 
{ 
    pref.Name = sapReadOnlyItems.Where(sapItem => sapItem.ItemValue == pref.ItemValue).FirstOrDefault().Name; 
} 
0

我不相信你想在特殊的C#語法做什麼,而是你需要使用常規的方法鏈接語法。有兩個選項:

方法1:

這裏是一個foreach擴展方法,如果你想使用LINQ語法使用它:

sapReadOnlyItems.ForEach(s => preferences.Single(p => p.ItemValue == s.ItemValue).Name = s.Name); 

使用這樣的:

public static void ForEach<T>(this IEnumerable<T> items, Action<T> action) 
{ 
    foreach(T item in items) 
    { 
     action(item); 
    } 
} 

方法#2:

如果你想更新的喜好回來,你可以這樣做:

var updatedPreferences = sapReadOnlyItems.Select(s => 
         { 
          var p = preferences.Single(p => p.ItemValue == s.ItemValue); 
          p.Name = s.Name; 
          return p; 
         }); 
+0

foreach所IEnumerable的... http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx http://blogs.msdn.com/b/馬洲/存檔/ 2011/09/21 /爲什麼-NO-的foreach方法上,IEnumerable的-interfac es.aspx – Maarten

2

你可以做加盟,並與標準的LINQ運營商指定的名稱:

var query = preferences.Join(sapReadOnlyItems, 
          p => p.ItemValue, 
          s => s.ItemValue, 
          (p, s) => { p.Name = s.Name; return p; }); 
4

我建議使用Lambda的foreach

preferences.ForEach(preference => 
       { 
        var sap = sapReadOnlyItems.FirstOrDefault(s => s.ItemValue = preference.ItemValue); 
        preference.Name = (sap != null) ? sap.Name : string.Empty; 
       }); 
相關問題