0

我仍在从 Microsoft 网站学习 lambda 和 Linq,并尝试自己编写一些简单的示例来更深入地了解这些很酷的东西。我学得越多,我就越觉得这些东西很有趣,但学习曲线很陡峭。再一次,我需要更多的帮助。

基本上,我有一个名为 item 的类,它具有 NodeID、Weight 和 Category 属性。

我还有一个名为 Recipient 的类,它代表接收者接收物品。

我还有一个二维布尔表,它显示了一个项目与另一个项目的交互。如果 ID 为 NodeID1 的 item1 不应该与 ID 为 Node2 的 item2 有,那么 table[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 的收件人,这样providedMatrix[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)

谢谢您的帮助!

4

2 回答 2

0

要有一个单行,这应该工作:

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.

于 2013-11-03T22:49:53.767 回答
0

我想我找到了自己问题的答案。我可能正确也可能不正确。如果我错了,请告诉我。

这就是我的想法:

recipients.Where((x,y)=>x.Value.getListItemInCategory(items[NodeID1].Category).Contains(y) && prohibitedMatrix[y][NodeID1]).Select(x=>x.Value.RecipientID).ToList()
于 2013-11-03T22:53:07.323 回答