如何在.NET Core中使用C#删除嵌套列表中的项目?

huangapple go评论78阅读模式
英文:

How to remove an item on nested list in .NET Core using C#?

问题

我需要使用C#从嵌套列表中移除一个项目。这是我的列表:

{
    "Name": "CC",
    "Categories": [
        { "description": "Visaa", "payCode": "v" },
        { "description": "Master", "payCode": "m" }
    ]
},
{
    "Name": "paypal",
    "Categories": [
        { "description": "paypal", "payCode": "p" }
    ]
}

我想要从CC类型中删除这个类别列表:

{
   "description": "Master",
   "payCode": "m"
}

之后,我的列表应该如下所示:

{
        "Name": "CC",
        "Categories": [
            { "description": "Visaa", "payCode": "v" }
        ]
 },
 {
        "Name": "paypal",
        "Categories": [
            { "description": "paypal", "payCode": "p" }
        ]
 }

我尝试了以下方法,但不确定如何做才能得到上面的列表:

payments.Find(x => x.Name == "CreditCard").PaymentOptions;
英文:

I have to remove an item from the nested list using C#. This is my list:

{
    "Name": "CC",
    "Categories": [
        { "description": "Visaa", "payCode": "v" },
        { "description": "Master", "payCode": "m" }
    ]
},
{
    "Name": "paypal",
    "Categories": [
        { "description": "paypal", "payCode": "p" }
    ]
}

I want to remove this category list from CC type:

{
   "description": "Master",
   "payCode": "m"
}

After that, my list should looks like this:

 {
        "Name": "CC",
        "Categories": [
            { "description": "Visaa", "payCode": "v" }
        ]
 },
 {
        "Name": "paypal",
        "Categories": [
            { "description": "paypal", "payCode": "p" }
        ]
 }

I tried the following but not sure how to do it to get the above list

payments.Find(x => x.Name == "CreditCard").PaymentOptions;

答案1

得分: 2

payments.Find(item => item.name == "CC")
        .Categories.Remove(cat => cat.payCode == 'm');
英文:
payments.Find(item => item.name == "CC")
        .Categories.Remove(cat => cat.payCode == 'm');

答案2

得分: 0

你需要从categories对象中移除元素,以下是一个示例...

using Newtonsoft.Json;

namespace tests
{
    public class Testing
    {
        public void Run()
        {

            var stringPayments = "[{\"Name\":\"CC\",\"Categories\":[{\"description\":\"Visaa\",\"payCode\":\"v\"},{\"description\":\"Master\",\"payCode\":\"m\"}]},{\"Name\":\"paypal\",\"Categories\":[{\"description\":\"paypal\",\"payCode\":\"p\"}]}]";
            var listPayments = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Payment>>(stringPayments);
            
            //移除前的列表
            Console.WriteLine("移除前的列表");
            PrintPayments(listPayments);

            //移除后的列表
            listPayments.Find(p => p.Name == "CC")
                            .Categories.RemoveAll(c => c.Description == "Master");
                            
            Console.WriteLine("\n移除后的列表");
            PrintPayments(listPayments);
            
        }

        public void PrintPayments(List<Payment> listPayments)
        {
            Console.WriteLine("---------开始-----------");
            foreach (var item in listPayments)
            {
                Console.WriteLine("- 名称: " + item.Name);
                Console.WriteLine("---- 类别 ----");
                foreach (var category in item.Categories)
                {   
                    Console.WriteLine("---- 描述: " + category.Description + ", 支付代码: " + category.Paycode);
                }
                
            }
            Console.WriteLine("---------结束------------");
        }

    }

    public class Payment
    {
        public string Name { get; set; }
        public List<PaymentCategory> Categories { get; set; }
    }

    public class PaymentCategory
    {
        public string Description { get; set; }
        public string Paycode { get; set; }
    }
}
英文:

You need to remove the element from categories object, here an example...

using Newtonsoft.Json;

namespace tests
{
    public class Testing
    {
        public void Run()
        {

            var stringPayments = &quot;[{\&quot;Name\&quot;:\&quot;CC\&quot;,\&quot;Categories\&quot;:[{\&quot;description\&quot;:\&quot;Visaa\&quot;,\&quot;payCode\&quot;:\&quot;v\&quot;},{\&quot;description\&quot;:\&quot;Master\&quot;,\&quot;payCode\&quot;:\&quot;m\&quot;}]},{\&quot;Name\&quot;:\&quot;paypal\&quot;,\&quot;Categories\&quot;:[{\&quot;description\&quot;:\&quot;paypal\&quot;,\&quot;payCode\&quot;:\&quot;p\&quot;}]}]&quot;;
            var listPayments = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;List&lt;Payment&gt;&gt;(stringPayments);
            
            //List before remove
            Console.WriteLine(&quot;List before remove&quot;);
            PrintPayments(listPayments);

            //List after remove
            listPayments.Find(p =&gt; p.Name == &quot;CC&quot;)
                            .Categories.RemoveAll(c =&gt; c.Description == &quot;Master&quot;);
                            
            Console.WriteLine(&quot;\nList after remove&quot;);
            PrintPayments(listPayments);
            
        }

        public void PrintPayments(List&lt;Payment&gt; listPayments)
        {
            Console.WriteLine(&quot;---------Start-----------&quot;);
            foreach (var item in listPayments)
            {
                Console.WriteLine(&quot;- Name: &quot; + item.Name);
                Console.WriteLine(&quot;---- Categories ----&quot;);
                foreach (var category in item.Categories)
                {   
                    Console.WriteLine(&quot;---- Description: &quot; + category.Description + &quot;, Paycode: &quot; + category.Paycode);
                }
                
            }
            Console.WriteLine(&quot;---------End------------&quot;);
        }

    }

    public class Payment
    {
        public string Name { get; set; }
        public List&lt;PaymentCategory&gt; Categories { get; set; }
    }

    public class PaymentCategory
    {
        public string Description { get; set; }
        public string Paycode { get; set; }
    }
}

答案3

得分: 0

使用LINQ语句,您只能查询数据,无法更改查询的数据。

如果您想在本地内存中更改数据,您需要获取对数据的引用,然后枚举已获取的引用以更改它。

如果数据存储在其他地方,例如数据库中,您需要特殊的方法来更改数据。如果您使用Entity Framework,您需要查询完整的项目(不使用Select),枚举已获取的数据以更改数据,然后调用SaveChanges。

回到您的问题。

由于您使用了Find,我假设您正在使用类似于Entity Framework的东西。

您忘记提供类的定义。我认为您有类似以下的类:

class PaymentCategory
{
    public string Name { get; set; }
    public string PayCode { get; set; } // 或者更好的是:枚举?
}

class PaymentMethods
{
    public string Name { get; set; }
    public virtual ICollection<PaymentCategory> Categories { get; set; }
}

要求:给定一系列PaymentMethods X和一个PaymentCategory Y,请给我一系列所有PaymentMethods X,其中属性Categories中不包含PaymentCategory Y。

您觉得这样如何:

IQueryable<PaymentMethod> paymentMethods = ...
PaymentCategory categoryToRemove = ...

IEnumerable<PaymentMethod> paymentMethodsWithoutCategory =
    paymentMethods.Select(paymentMethod => new PaymentMethod
    {
        Name = paymentMethod.Name,

        // 仅保留那些PaymentCategories,其Name或PayCode与categoryToRemove的Name / PayCode不相同
        Categories = paymentMethod.Categories
            .Where(category => category.Name != categoryToRemove.Name
                            || category.PayCode != categoryToRemove.PayCode)
            .ToList(),
     });

简而言之:对于序列中的每个paymentMethod,创建一个新的paymentMethod,其中包含以下属性的值:

  • Name:使用paymentMethod的名称
  • Categories:从paymentMethod的Categories序列中获取每个paymentCategory,这些paymentCategory的Name或PayCode与categoryToRemove的Name / PayCode不同。然后将其制作成一个列表。
英文:

With a LINQ statement you can only query data, you cannot change the queried data

If you want to change the data in local memory, you'll have to fetch references to the data, and then enumerate the fetched references to change it.

If the data is somewhere else, for instance in a database, You need special methods to change the data. If you use Entity Framework, you'll have to query the complete items (= not use Select), enumerate the fetched data to change the data and then call SaveChanges.

Back to your problem.

As you are using Find, I assume you are using something like Entity Framework.

You forgot to give us your classes. I think you have classes similar to the following:

class PaymentCategory
{
    public string Name {get; set;}
    public string PayCode {get; set;}      // or even better: enum?
}

class PaymentMethods
{
    public string Name {get; set;}
    public virtual ICollection&lt;PaymentCategory&gt; Categories {get; set;}
}

Requirement: Given a sequence of PaymentMethods X and one PaymentCategory Y, give me the sequence of all PaymentMethods X, without the PaymentCategory Y in property Categories.

How about this:

IQueryable &lt;PaymentMethod&gt; paymentMethods = ...
PaymentCategory categoryToRemove = ...

IEnumerable&lt;PaymentMethod&gt; paymentMethodsWithoutCategory =
    paymentMethods.Select(paymentMethod =&gt; new PaymentMethod
    {
        Name = paymentMethod.Name,

        // keep only those PaymentCategories that have not Name / PayCode
        // equal to the ones in categoryToRemove
        Categories = paymentMethod.Categories
            .Where(category =&gt; category.Name != categoryToRemove.Name
                            || category.PayCode != categoryToRemove.PayCode)
            .ToList(),
     });

In words: from every paymentMethod in the sequence of paymentMethods, make one new paymentMethod containing the following values for the property:

  • Name: use the name of the paymentMethod
  • Categories: take every paymentCategory from the sequence of Categories in the paymentMethod that have either a Name or a Paycode different than the Name / Paycode in categoryToRemove. Make a list from this.

huangapple
  • 本文由 发表于 2023年7月27日 21:39:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76780350.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定