我有一个Linq查询,我需要在select子句中根据列表中是否存在记录来获取值。这是我的疑问:
var records = (from il in itemList
join ci in catalogueItemList on il.CatalogueItemID equals ci.CatalogueItemID
join pd in publicationDataList on il.CatalogueItemID equals pd.CatalogueItemID
select new { il.ItemID, pd.ISBN, ci.Title, ci.CatalogueItemID, il.LocationID, il.Missing, }).ToList();
我有一个名为itemCheckoutDictionary的Dictionary,我在伪代码中想要的是:
if (itemCheckDictionary.ContainsKey(i.itemID)) then "Checked Out" else "In"
我需要在我的select子句中,我不知道如何实现这一点。
答案 0 :(得分:9)
您是否尝试过ternary operator?
string s = itemCheckDictionary.ContainsKey(i.itemID) ? "Checked Out" : "In";
答案 1 :(得分:1)
您不需要if,您可以使用:
itemCheckDictionary.ContainsKey(i.itemID) ? "Checked Out" : "In"
答案 2 :(得分:1)
我经常喜欢使用小辅助函数来实现它:
var getStatus = new Func<int, string>(itemID => {
return itemCheckDictionary.ContainsKey(itemID) ? "Checked Out" : "In";
});
var records = (from il in itemList
join ci in catalogueItemList on il.CatalogueItemID equals ci.CatalogueItemID
join pd in publicationDataList on il.CatalogueItemID equals pd.CatalogueItemID
select new {
// other properties
Status = getStatus(i.ItemID) }).ToList();