【问题标题】:Linq lambda using whereLinq lambda 使用 where
【发布时间】:2013-11-04 06:53:07
【问题描述】:

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

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

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

我还有一个二维布尔表,它显示了一个项目与另一个项目的交互。如果 ID 为 NodeID1 的 item1 不应该与 ID 为 Node2 的 item2 有,那么 table[Node1][Node2] 的值应该是 true。

我想要找出的是接收不应该一起接收的东西的收件人列表,换句话说,在表中具有 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)

感谢您的帮助!

【问题讨论】:

    标签: c# linq lambda


    【解决方案1】:

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

    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

    【讨论】:

    • 谢谢巴托兹。我忘记使用扩展名了。
    【解决方案2】:

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

    这是我的想法:

    recipients.Where((x,y)=>x.Value.getListItemInCategory(items[NodeID1].Category).Contains(y) && prohibitedMatrix[y][NodeID1]).Select(x=>x.Value.RecipientID).ToList()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多