[英]Where condition inside lambda expression c#
我有一個像
public class Program
{
public int ID { get; set; }
public bool IsActive { get; set; }
public string Title { get; set; }
}
和
public class EMetrics
{
public int ID { get; set; }
public bool IsActive { get; set; }
public string Title { get; set; }
public List<Program> Programs { get; set; }
}
我有類似的存儲庫方法,
IEnumerable<EMetrics> IEmetricsRepository.GetAllByProgram(params int[] programIds)
{
var metrics = EntitySet
.Where(x => programIds.Contains(x.Programs.Select(x => x.ID)))
.ToList();
return metrics;
}
[上面的代碼拋出構建錯誤]
在這里,只有我遇到問題才能根據程序Ids數組參數獲取EMetrics。
我想要列出與該程序關聯的Emetrics。
您在LINQ中錯誤地訪問了相同的輸入參數。 應該通過更改內部Select來使用其他參數來重構它:
IEnumerable<EMetrics> IEmetricsRepository.GetAllByProgram(params int[] programIds)
{
var metrics = EntitySet
.Where(x => programIds.Contains(x.Programs.Select(y => y.ID)))
.ToList();
return metrics;
}
因此,您想檢查一個集合中的所有元素是否都存在於另一個集合中。 在LINQ中,可以將Except和Any組合使用:
var metrics = EntitySet
.Where(x => x.Programs.Select(p => p.ID).Except(programIds).Any())
.ToList();
Array.Contains
您當前的代碼失敗,因為Array.Contains
期望單個項目(在這種情況下為int),而您卻給出了一個完整的枚舉
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.