使用linq从列表中删除元素

时间:2019-02-12 22:34:11

标签: c# arrays linq removeall

我有ct_CompleteOrder类型的对象,并具有以下类:

ct_CompleteOrder类

public partial class ct_CompleteOrder {
    private ct_CompleteOrderPayments paymentsField;
}

ct_CompleteOrderPayments类

public partial class ct_CompleteOrderPayments {
    private ct_Payment[] paymentField;
    public ct_Payment[] Payment {
    get {
        return this.paymentField;
        }
    set {
        this.paymentField = value;
        }
    }
}

ct_Payment类

public partial class ct_Payment {
    public string type{get; set;}
}

我想根据类型值删除ct_Payment数组的元素。我尝试先将其转换为列表以应用RemoveAll,但无法正常工作。我在做什么错了?

completeOrder.Payments.Payment.ToList().RemoveAll(x => x.type == "AUTO");

2 个答案:

答案 0 :(得分:1)

将数组复制到列表然后应用linq时,链接仅从列表中删除,而不是从数组中删除。

如果要保持数组大小不变,但要留有空格,则应使用for循环遍历数组,并将x.type ==“ AUTO”的数组设置为null。

for(int i = 0; i < completeOrder.Payments.Payment.Length; i++)
{
    if(completeOrder.Payments.Payment[i].type == "AUTO")
    {
        completeOrder.Paymets.Payment[i] == null;
    }
}

否则,如果要更改数组的实际大小,只需将付款设置为更改后的列表即可。 RemoveAll不会返回列表(它返回void),因此您最好反转逻辑,而只需使用Where语句

completeOrder.Payments.Payment = completeOrder.Payments.Payment.Where(x => x.type != "AUTO").ToArray();

答案 1 :(得分:1)

您为什么要完全转换为列表?我认为这是不必要的步骤。我为您创建了一个DotNetFiddle,目的是向您展示我对问题的理解。

C#

using System;
using System.Runtime;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string[] arrayOfItems = new string[5] {"Apple", "Banana", "Orange", "Apple", "Grape"};

        var arrayWithoutApples = arrayOfItems.Where(x => x != "Apple").ToArray();

        foreach(var item in arrayWithoutApples)
        {
            Console.WriteLine(item);    
        }

        // Output:

        // Banana
        // Orange
        // Grape

    }
}

我的示例肯定不会像您的代码那样复杂,但是如果您有一个值数组,并且您想通过基于特定条件删除元素来“缩小”该数组,那么您就不必事先转换为列表。使用Where检索您想要或不想要的项目,然后使用ToArray()将结果转换为数组变量。

让我知道这是否有帮助。

相关问题