我有2个实体,我需要找到一种方法来避免使用两个foreach函数:
public class IzigoKeyword
{
public int Id { get; set; }
public string Name { get; set; }
// Navigation properties
public Address Address { get; set; }
public virtual ICollection<Keyword> Keywords { get; set; }
}
public class Keyword
{
public int Id { get; set; }
}
直到现在的功能:
public IList<int> GetKeywordIdsFromIzigoKeywordIds(IList<int> izigoKeywordIds)
{
IList<int> keywordIds = new List<int>();
foreach (var izigoKeywordId in izigoKeywordIds)
{
var keywords = _izigoKeywordRepository.Query.Where(ik => ik.Id == izigoKeywordId).Select(ik => ik.Keywords);
foreach (var keyword in keywords)
{
keywordIds.Add(keyword.Select(k => k.Id).FirstOrDefault());
}
}
return keywordIds;
}
如果没有2个foreach函数,我怎么能这样做?
感谢。
答案 0 :(得分:6)
return ids.SelectMany(id =>
query.Where(ik => ik.Id == id)
.SelectMany(ik => ik.Keywords)
.Select(k => k.Id)
);