removeall을 특정 수의 객체로 제한하십시오
문제
나는 함께 일하고있다 List<T>
여기에는 부모와 어린이 개체가 모두 포함되어 있습니다. 이 목록에서 어린이 개체는 관련 부모 객체를 알고 있으며 그 반대도 마찬가지입니다. 이 목록을 사용하여 부모가 특정 유형 일 때 최대 4 명의 어린이 개체가 목록에서 제거되는 비즈니스 규칙을 구현하려고합니다. 이 유형의 부모가 20 명의 자녀가있는 경우 4 개의 자녀가 목록에서 제거 해야하는 경우 다르게 넣으십시오.
내가 여기에 설명한 코드는 그럴 것입니다 RemoveAll
조건을 충족시키는 어린이들의 물체. 이것은 예상되지만 내가하고 싶은 것은 제한입니다. RemoveAll
4 명의 자녀 만 제거합니다. 이것을 할 수있는 수단이 있습니까? RemoveAll
아니면 내가 사용해야 할 또 다른 방법이 있습니까?
myList.RemoveaAll(item =>
item.Child && "Foo".Equals(item.Parent.SpecialType));
해결책
그만큼 가져가다 확장 방법은 ienumerable에서 첫 번째 n 수의 일치를 잡는 데 사용됩니다. 그런 다음 경기를 통해 반복하여 목록에서 제거 할 수 있습니다.
var matches = myList.Where(item => item.Child && "Foo".Equals(item.Parent.SpecialType)).Take(someNumber).ToList();
matches.ForEach(m => myList.Remove(m));
다른 팁
어떤 4가 중요합니까? 그렇지 않은 경우 사용할 수 있습니다 .Take(4)
4 명의 자녀 목록을 만들려면 반복 및 Remove
4 ...
이 시도:
int i = 0;
myList.Removeall(item =>
item.Child && "Foo".Equals(item.Parent.SpecialType) && i++ < 4);
테스트하지는 않았지만 작동해야합니다.
사용하지 않는 이유는 무엇입니까? Take
기능?
다음과 같은 일반 목록 인터페이스 위에 제작하기 위해 확장 방법을 작성할 수도 있습니다.
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) ;
}
}
}
제휴하지 않습니다 StackOverflow