[英]In linq, how do I take specific parameter out of a list and build new list of different type?
我是linq的新手。 到目前為止,我一直主要使用這樣的linqTOsql: MyRepository.Mytable.Where(x => x.id == 2)
。
我想知道如何從該類型的查詢中獲取一個列表,並將一個特定的參數放入一個新的簡單列表,如List<long>
。
所以我得到了這樣的記錄:
List<Entry2Cats> e2c = genesisRepository.Entry2Cats.Where( x => x.streamEntryID == id).ToList()
我想獲得e2c
每個項目的類別ID參數,以便我可以將其移動到List<long>
。
顯然,這可以通過foreach
相當簡單地完成:
List<Entry2Cats> e2c = genesisRepository.Entry2Cats
.Where(x => x.streamEntryID == id)
.ToList();
List<long> e2cCatIDs = new List<long>();
foreach (Entry2Cats item in e2c)
{
e2cCatIDs.Add(item.catID);
}
這可以用linq完成嗎? 如果可以的話,我是否應該為此煩惱或者foreach
一樣好?
List<long> ids = genesisRepository.Entry2Cats
.Where(x => x.streamEntryID == id)
.Select(a => a.catID)
.ToList();
只需使用Select即可獲取ID。
List <Long> e2c = genesisRepository.Entry2Cats
.Where(x => x.streamEntryID == id)
.Select(x => x.catID)
.ToList();
List<long> e2cCatIDs = e2c.Select(e => e.catID).ToList();
或直接在查詢中選擇
List<long> e2cCatIDs = (from x in genesisRepository.Entry2Cats
where x.streamEntryID == id
select x.catID).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.