0

我正在使用一个List<T>包含父对象和子对象的对象。在这个列表中,子对象知道它们相关的父对象,反之亦然。使用此列表,我正在尝试实现一个业务规则,其中当父对象属于某种类型时,最多将从列表中删除 4 个子对象。换句话说,如果这种类型的父母有 20 个孩子,其中 4 个应该从列表中删除。

我在这里概述的代码将RemoveAll满足条件的子对象。这是意料之中的,但我想做的是限制RemoveAll只移除 4 个孩子。有没有办法做到这一点,RemoveAll或者我应该使用另一种方法?

myList.RemoveaAll(item =>
  item.Child && "Foo".Equals(item.Parent.SpecialType));
4

5 回答 5

5

Take扩展方法用于从 IEnumerable 中获取前 n 个匹配项。然后,您可以遍历匹配项并将它们从列表中删除。

var matches = myList.Where(item => item.Child && "Foo".Equals(item.Parent.SpecialType)).Take(someNumber).ToList();
matches.ForEach(m => myList.Remove(m));
于 2009-12-11T19:03:17.157 回答
2

哪个4重要吗?如果没有,您可以使用.Take(4)创建一个包含 4 个子项的列表,然后遍历和Remove4...

于 2009-12-11T19:04:07.000 回答
1

试试这个:

int i = 0;
myList.Removeall(item =>
  item.Child && "Foo".Equals(item.Parent.SpecialType) && i++ < 4);

请注意,我尚未对其进行测试,但它应该可以工作

于 2009-12-11T19:23:16.023 回答
0

为什么不使用该Take功能?

于 2009-12-11T19:02:26.627 回答
0

您还可以编写一个扩展方法来构建在普通列表接口之上,如下所示:

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

namespace App
{

    public static class ListExtension
    {
        public static int RemoveAll<T>(this List<T> list, Predicate<T> match, uint maxcount)
        {
            uint removed = 0;
            Predicate<T> wrappingmatcher = (item) =>
            {
                if (match(item) && removed < maxcount)
                {
                    removed++;
                    return true;
                }
                else
                {
                    return false;
                }
            };
            return list.RemoveAll(wrappingmatcher);
        }
    }

    public interface IHero { }
    public class Batman : IHero { }

    public class HeroCompilation
    {
        public List<IHero> Herolist;

        public HeroCompilation()
        {
            Herolist = new List<IHero>();
        }

        public void AddBatmans(int count){
            for (int i = 1; i <= count; i++) Herolist.Add(new Batman());
        }
    }

    class Program
    {
        static void ConsoleWriteBatmanCount(List<IHero> hero)
        {
            Console.WriteLine("There are {0} Batmans", hero.Count);
        }


        static void Main(string[] args)
        {
            HeroCompilation tester = new HeroCompilation();
            ConsoleWriteBatmanCount(tester.Herolist);
            tester.AddBatmans(10);
            ConsoleWriteBatmanCount(tester.Herolist);
            tester.Herolist.RemoveAll((x) => { return true; }, 4);
            ConsoleWriteBatmanCount(tester.Herolist);
            tester.Herolist.RemoveAll((x) => { return true; }, 4);
            ConsoleWriteBatmanCount(tester.Herolist);
            tester.Herolist.RemoveAll((x) => { return true; }, 4);
            ConsoleWriteBatmanCount(tester.Herolist);
            while (true) ;
        }
    }
}
于 2012-06-12T17:04:34.923 回答