修改通用列表中的多个条目(无需为每个条目创建新变量)

时间:2017-07-11 14:22:18

标签: c# linq generics

我希望使用泛型方法更改列表条目的状态。

我的代码如下。我想出了如何更改一个条目(例如,鸡2号),但我想一次更改多个鸡状态,而不是单独分配给变量。

最终,我想用一种方法将鸡的状态从“活着”改为“死亡”(当惠普 - 尚未在代码中 - 触发零时触发)。

class Chicken_Test
{
    class Chicken
    {
        public Chicken(int inNumber, string status)
        {
            this.Number = inNumber;  // UNIQUE ID
            this.Status = status;
        }

        public int Number { get; set; }
        public string Status { get; set; }
    }

    public static void Main()
    {
        var chickens = new List<Chicken>();
        for (int i = 0; i < 100; i++)
        {
            chickens.Add(new Chicken(i,  "Alive"));
        }

        int testnummer = 2;

        var chickenTwo = chickens.SingleOrDefault(c => c.Number == testnummer);
        chickenTwo.Status = "Dead";

        var chickensAlive = chickens
                .Where(r => r.Status == "Alive")
                .GroupBy(c => c.Number)
                .Select(r => new
                {
                    Status = r.Key,
                    Count = r.Count()
                }).ToList();
    }
}

4 个答案:

答案 0 :(得分:2)

你甚至需要一种方法吗?

class Chicken
{
    public string Status
    {
        get { return _hp <= 0 ? "Dead" : "Alive"; }
    }
}

可替换地。

class Chicken
{
    private int _hp;

    public int HP
    {
        get { return _hp; }
        set
        {
            if (_hp != value)
            {
                _hp = value;
                OnHPChanged();
            }
        }
    }

    public string Status { get; set; }

    private void OnHPChanged()
    {
        if (HP <= 0)
            Status = "Dead";
        else
            Status = "Alive";
    }
}

答案 1 :(得分:2)

void KillChicken(Chicken chicken)
{
        chicken.Status = "Dead";
}

int[] testnummer = { 2,3,5,6};
foreach(var ch in chickens.Where(c=>testnummer.Contains(c.Number))
       KillChicken(ch);

答案 2 :(得分:0)

你试过这个吗?

chickens.ForEach(chicken => chicken.Status = "Dead")

通过这种方式,我建议在Status变量中使用枚举而不是字符串,这样你的代码看起来就像这样

class Chicken
{
    public enum ChickenStatus
    {
        Dead,
        Alive
    }

    public Chicken(int inNumber, ChickenStatus status)
    {
        this.Number = inNumber;
        this.Status = status;
    }

    public int Number { get; set; }
    public ChickenStatus Status { get; set; }
}

也许用struct替换class,看起来更合适。

答案 3 :(得分:0)

int[] testnummer = { 2,3,5,6};

chickens = chickens.Select(x => new Chicken(x.Number,x.Status)
            {
             Status =  testnummer.Contains(x.Number)? "Dead" : x.Status     
            }).ToList(); 

OR

无法创建新列表,您可以更新当前列表。

chickens.Select(x => { x.Status = testnummer.Contains(x.Number) ? "Dead" : x.Status; return x;}).ToList()