programing tip

C #의 목록에서 항목을 제거하는 방법은 무엇입니까?

itbloger 2020. 6. 6. 08:41
반응형

C #의 목록에서 항목을 제거하는 방법은 무엇입니까?


다음과 같이 결과 목록에 저장된 목록이 있습니다.

var resultlist = results.ToList();

다음과 같이 보입니다 :

ID FirstName  LastName
-- ---------  --------
1  Bill       Smith
2  John       Wilson
3  Doug       Berg

목록에서 ID 2를 어떻게 제거합니까?


List<T> 사용할 수있는 두 가지 방법이 있습니다.

항목의 색인을 알고 있으면 RemoveAt (int index)를 사용할 수 있습니다. 예를 들면 다음과 같습니다.

resultlist.RemoveAt(1);

또는 Remove (T item)을 사용할 수 있습니다 .

var itemToRemove = resultlist.Single(r => r.Id == 2);
resultList.Remove(itemToRemove);

항목이 실제로 존재하는지 확실하지 않은 경우 SingleOrDefault 를 사용할 수 있습니다 . 항목이 없으면 SingleOrDefault반환 null합니다 ( Single항목을 찾을 수 없으면 예외가 발생 함). 중복 값이있는 경우 두 가지가 모두 발생합니다 (같은 두 항목 id).

var itemToRemove = resultlist.SingleOrDefault(r => r.Id == 2);
if (itemToRemove != null)
    resultList.Remove(itemToRemove);

resultList = results.Where(x=>x.Id != 2).ToList();

내가 좋아하는 작은 Linq 도우미가 있습니다. 구현하기 쉽고 "아닌 곳"조건의 쿼리를 좀 더 읽기 쉽게 만들 수 있습니다.

public static IEnumerable<T> ExceptWhere<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
    return source.Where(x=>!predicate(x));
}

//usage in above situation
resultList = results.ExceptWhere(x=>x.Id == 2).ToList();

짧은 답변 :
제거 (목록에서 results)

results.RemoveAll(r => r.ID == 2);ID가 2 인 항목이 results제자리 제거됩니다 .

필터 (원본 목록에서 제거하지 않고 results) :

var filtered = result.Where(f => f.ID != 2);ID가 2 인 항목을 제외한 모든 항목을 반환합니다.

자세한 답변 :

.RemoveAll()제거하려는 항목 ID 목록을 가질 수 있기 때문에 매우 유연 하다고 생각 합니다. 다음 예를 고려하십시오.

당신이 가지고 있다면:

class myClass {
    public int ID; public string FirstName; public string LastName;
}

results다음과 같이 값을 할당했습니다 .

var results=new List<myClass> {
    new myClass()  { ID=1, FirstName="Bill", LastName="Smith" },
    new myClass()  { ID=2, FirstName="John", LastName="Wilson" },
    new myClass()  { ID=3, FirstName="Doug", LastName="Berg" },
    new myClass()  { ID=4, FirstName="Bill", LastName="Wilson" },
};

그런 다음 제거 할 ID 목록을 정의 할 수 있습니다.

var removeList = new List<int>() { 2, 3 };

그리고 이것을 사용하여 제거하십시오.

results.RemoveAll(r => removeList.Any(a => a==r.ID));

항목 2와 3제거하고에 지정된대로 항목 1과 4를 유지합니다 removeList. 참고 이 자리에서 일어나는, 그래서 필요한 추가의 할당은이 없다는 것을.

Of course, you can also use it on single items like:

results.RemoveAll(r => r.ID==4);

where it will remove Bill with ID 4 in our example.


DotNetFiddle: Run the demo


There is another approach. It uses List.FindIndex and List.RemoveAt.

While I would probably use the solution presented by KeithS (just the simple Where/ToList) this approach differs in that it mutates the original list object. This can be a good (or a bad) "feature" depending upon expectations.

In any case, the FindIndex (coupled with a guard) ensures the RemoveAt will be correct if there are gaps in the IDs or the ordering is wrong, etc, and using RemoveAt (vs Remove) avoids a second O(n) search through the list.

Here is a LINQPad snippet:

var list = new List<int> { 1, 3, 2 };
var index = list.FindIndex(i => i == 2); // like Where/Single
if (index >= 0) {   // ensure item found
    list.RemoveAt(index);
}
list.Dump();        // results -> 1, 3

Happy coding.


You don't specify what kind of list, but the generic List can use either the RemoveAt(index) method, or the Remove(obj) method:

// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);

// RemoveAt(index)
resultList.RemoveAt(1);

More simplified:

resultList.Remove(resultList.Single(x => x.Id == 2));

there is no needing to create a new var object.


... or just resultlist.RemoveAt(1) if you know exactly the index.


{
    class Program
    {
        public static List<Product> list;
        static void Main(string[] args)
        {

            list = new List<Product>() { new Product() { ProductId=1, Name="Nike 12N0",Brand="Nike",Price=12000,Quantity=50},
                 new Product() { ProductId =2, Name = "Puma 560K", Brand = "Puma", Price = 120000, Quantity = 55 },
                 new Product() { ProductId=3, Name="WoodLand V2",Brand="WoodLand",Price=21020,Quantity=25},
                 new Product() { ProductId=4, Name="Adidas S52",Brand="Adidas",Price=20000,Quantity=35},
                 new Product() { ProductId=5, Name="Rebook SPEED2O",Brand="Rebook",Price=1200,Quantity=15}};


            Console.WriteLine("Enter ProductID to remove");
            int uno = Convert.ToInt32(Console.ReadLine());
            var itemToRemove = list.Find(r => r.ProductId == uno);
            if (itemToRemove != null)
                list.Remove(itemToRemove);
            Console.WriteLine($"{itemToRemove.ProductId}{itemToRemove.Name}{itemToRemove.Brand}{itemToRemove.Price}{ itemToRemove.Quantity}");
            Console.WriteLine("------------sucessfully Removed---------------");

            var query2 = from x in list select x;
            foreach (var item in query2)
            {
                /*Console.WriteLine(item.ProductId+" "+item.Name+" "+item.Brand+" "+item.Price+" "+item.Quantity );*/
                Console.WriteLine($"{item.ProductId}{item.Name}{item.Brand}{item.Price}{ item.Quantity}");
            }

        }

    }
}

참고URL : https://stackoverflow.com/questions/10018957/how-to-remove-item-from-list-in-c

반응형