我有2个对象列表。一个有价值观,另一个有名字和价值观。我想查找其他列表中的值并将结果写入pref.Name。我知道我可以用foreach做到这一点,但我认为在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 :(得分:4)
我建议使用Lambda foreach
preferences.ForEach(preference =>
{
var sap = sapReadOnlyItems.FirstOrDefault(s => s.ItemValue = preference.ItemValue);
preference.Name = (sap != null) ? sap.Name : string.Empty;
});
答案 1 :(得分:2)
您可以使用标准linq运算符进行连接并指定名称:
var query = preferences.Join(sapReadOnlyItems,
p => p.ItemValue,
s => s.ItemValue,
(p, s) => { p.Name = s.Name; return p; });
答案 2 :(得分:0)
我想出了这个:
foreach (Preference pref in preferences)
{
pref.Name = sapReadOnlyItems.Where(sapItem => sapItem.ItemValue == pref.ItemValue).FirstOrDefault().Name;
}
答案 3 :(得分:0)
我不相信你想要的东西可以在特殊的c#语法中完成,而是你需要使用常规的方法链接语法。两个选项:
方法#1:
如果你想将它与Linq语法一起使用,这是一个foreach扩展方法:
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;
});