[英]Linq lambda using where
我仍在從Microsoft網站學習lambda和Linq,並嘗試自己寫一些簡單的示例,以更深入地了解這些很棒的東西。 我學得越多,我就會發現這些東西很有趣,但學習難度卻很大。 再一次,我將需要更多幫助。
基本上,我有一個名為item的類,它具有屬性NodeID,Weight和Category。
我還有一個名為“收件人”的類,它表示收件人接收項目。
我還有一個二維布爾表,顯示一個項目與另一個項目的交互。 如果不應將ID為NodeID1的item1與ID為Node2的item2一起使用,則表[Node1] [Node2]的值應為true。
我試圖找出的是接收到的東西的收件人列表,這些東西不應該一起接收,換句話說,那些東西在表中具有真值。
public class Recipient
{
private Dictionary<int,item> _itemsReceivedList=new Dictionary<int,item>(); //itemID
private int _recipientID;
public int RecipientID{ get; set; }
public List<int> getListItemInCategory(int category)
{
return _itemsReceivedList.Where(x => x.Value.Category == category).Select(x => x.Value.NodeID).ToList();
}
}
public class item
{
public int NodeID { get; set; }
public int Weight { get; set; }
public int Category { get; set; }
}
在我的主程序中:
private bool[][] prohibitedMatrix; //prohibitedMatrix[NodeID1][NodeID2]=true means it is prohibited to have Item NodeID1 and NodeID2 together
private Dictionary<int,Recipient> recipients = new Dictionary<int,Recipient>();
private Dictionary<int, item> items = new Dictionary<int,item>();
給定一個具有NodeID1的項目,請在_itemReceivedList中找到具有x的收件人,以使被禁止的矩陣[x.NodeID] [NodeID1] = true
recipients.Where(x=>x.Value.getListItemInCategory(items[NodeID].Category)
&& "The NodeID in listItemInCategory and NodeID1 is not
true)
.Select(x=>x.Value.RecipientID)
謝謝您的幫助!
要設置一個班輪,應該可以:
var result = recipients
.Values
.Select(r => new
{
RecipientID = r.RecipientID,
Items = r.getListItemInCategory(items[NodeID].Category)
})
.Where(ri => ri.Items.Any(i => prohibitedMatrix[i.NodeID][NodeID]))
.Select(ri => ri.RecipientID);
或這個:
var result = recipients
.Values
.Where(r => r
.getListItemInCategory(items[NodeID].Category)
.Any(i => prohibitedMatrix[i.NodeID][NodeID]))
.Select(r => r.RecipientID);
但是最好在此處引入一些實用程序功能並將其分區。 或使用普通的foreach
。
我想我找到了自己問題的答案。 我可能正確也可能不正確。 如果我錯了,請告訴我。
我是這樣認為的:
recipients.Where((x,y)=>x.Value.getListItemInCategory(items[NodeID1].Category).Contains(y) && prohibitedMatrix[y][NodeID1]).Select(x=>x.Value.RecipientID).ToList()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.