在List<>中查找元素包含两个值

时间:2016-07-27 09:06:12

标签: c# list

使用我的两个值来获取List项目时遇到问题。

类别:

class Movement
{
    public int movX;
    public int movY;

}

代码:

void checkMovement()
{
    List<Movement> lstMovement = new List<Movement>();
    Movement currentMovement = new Movement();
    currentMovement.movX = 1; currentMovement.movY = 1; lstMovement.Add(currentMovement);
    currentMovement.movX = 1; currentMovement.movY = 3; lstMovement.Add(currentMovement);
    currentMovement.movX = 1; currentMovement.movY = 4; lstMovement.Add(currentMovement);
    currentMovement.movX = 2; currentMovement.movY = 2; lstMovement.Add(currentMovement);
    currentMovement.movX = 2; currentMovement.movY = 4; lstMovement.Add(currentMovement);
    currentMovement.movX = 3; currentMovement.movY = 5; lstMovement.Add(currentMovement);
    Movement curMovement = lstMovement.Find(item => item.movX == 1 && item.movY == 3);
    Console.WriteLine(curMovement.movX + ", " + curMovement.movY);
}

如果我要使用一个值来Find,那么效果会非常好。

这个例子:

Movement curMovement = lstMovement.Find(item => item.movX == 3);

值为movX = 3且movY = 5.

我可以使用这种语法使用两个表达式来查找列表对象吗?

4 个答案:

答案 0 :(得分:2)

您忘记使用getter和setter,因此所有属性都为null。下面的代码工作正常。

    using System;
    using System.Collections.Generic;
    using System.Linq;                      

    public class Movement
    {
        public int movX {get; set;}
        public int movY {get; set;}    
    }

    public class Program
    {
        public static void Main()
        {

            List<Movement> lstMovement = new List<Movement>();     

            lstMovement.Add(new Movement() {movX = 1, movY = 3});
            lstMovement.Add(new Movement() {movX = 1, movY = 3});
            lstMovement.Add(new Movement() {movX = 2, movY = 2});
            lstMovement.Add(new Movement() {movX = 2, movY = 4});
            lstMovement.Add(new Movement() {movX = 3, movY = 5});       

            var curMovement = lstMovement.FirstOrDefault(item => item.movX == 1 && item.movY == 3);

            Console.WriteLine(curMovement.movX + ", " + curMovement.movY);      

        }
    }

答案 1 :(得分:0)

使用&amp;&amp;

Movement curMovement = lstMovement.FirstOrDefault(item => item.movX == 3 && item.movY == 5);

答案 2 :(得分:0)

您正在重复使用同一个对象并一遍又一遍地添加它,如commented by J. Steen。要解决此问题,请每次都创建一个新实例:

lstMovement.Add(new Movement() { movX = 1, movY = 1 });
...

要获取列表,请使用Where

IEnumerable<Movement> curMovements = lstMovement.Where(item => item.movX == 3);

答案 3 :(得分:0)

您可以使用Where扩展方法来实现此目的,如: -

  1. 如果您只对第一项感兴趣,那么:

    Movement curMovement = lstMovement.FirstOrDefault(item => item.movX == 1 && item.movY == 3);
    
  2. 如果您对列表感兴趣,那么

    List<Movement> curMovement = lstMovement.Where(item => item.movX == 1 && item.movY == 3).ToList();