csharp - linq tolist c#




使用LINQ從List<T>中移除元素 (10)

假設我有LINQ查詢,例如:

var authors = from x in authorsList
              where x.firstname == "Bob"
              select x;

鑑於authorsList的類型是List<Author> ,我怎樣才能從authorsList中刪除由查詢返回給Author元素?

或者authorsList一種說法,我怎樣才能從authorsList刪除所有名字相同的Bob?

注意:這是針對該問題的簡化示例。


LINQ起源於函數式編程,它強調對象的不變性,所以它不提供內置方式來原地更新原始列表。

關於不變性的說明(摘自另一個SO答案):

這裡是維基百科定義的不變性(鏈接)

“在面向對象和函數式編程中,不可變對像是一個對象,它的狀態在創建後不能被修改。”


以下是從列表中刪除元素的示例。

 List<int> items = new List<int>() { 2, 2, 3, 4, 2, 7, 3,3,3};

 var result = items.Remove(2);//Remove the first ocurence of matched elements and returns boolean value
 var result1 = items.RemoveAll(lst => lst == 3);// Remove all the matched elements and returns count of removed element
 items.RemoveAt(3);//Removes the elements at the specified index

你可以用兩種方法刪除

var output = from x in authorsList
             where x.firstname != "Bob"
             select x;

要么

var authors = from x in authorsList
              where x.firstname == "Bob"
              select x;

var output = from x in authorsList
             where !authors.Contains(x) 
             select x;

我有同樣的問題,如果你想根據你的條件簡單的輸出,那麼第一個解決方案更好。


如果您確實需要刪除項目,那麼Except()如何呢?
您可以基於新列表進行刪除,或者通過嵌套Linq進行即時刪除。

var authorsList = new List<Author>()
{
    new Author{ Firstname = "Bob", Lastname = "Smith" },
    new Author{ Firstname = "Fred", Lastname = "Jones" },
    new Author{ Firstname = "Brian", Lastname = "Brains" },
    new Author{ Firstname = "Billy", Lastname = "TheKid" }
};

var authors = authorsList.Where(a => a.Firstname == "Bob");
authorsList = authorsList.Except(authors).ToList();
authorsList = authorsList.Except(authorsList.Where(a=>a.Firstname=="Billy")).ToList();

我徘徊,如果RemoveAll和Except之間有什麼區別和使用HashSet的優點,所以我做了快速性能檢查:)

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

namespace ListRemoveTest
{
    class Program
    {
        private static Random random = new Random( (int)DateTime.Now.Ticks );

        static void Main( string[] args )
        {
            Console.WriteLine( "Be patient, generating data..." );

            List<string> list = new List<string>();
            List<string> toRemove = new List<string>();
            for( int x=0; x < 1000000; x++ )
            {
                string randString = RandomString( random.Next( 100 ) );
                list.Add( randString );
                if( random.Next( 1000 ) == 0 )
                    toRemove.Insert( 0, randString );
            }

            List<string> l1 = new List<string>( list );
            List<string> l2 = new List<string>( list );
            List<string> l3 = new List<string>( list );
            List<string> l4 = new List<string>( list );

            Console.WriteLine( "Be patient, testing..." );

            Stopwatch sw1 = Stopwatch.StartNew();
            l1.RemoveAll( toRemove.Contains );
            sw1.Stop();

            Stopwatch sw2 = Stopwatch.StartNew();
            l2.RemoveAll( new HashSet<string>( toRemove ).Contains );
            sw2.Stop();

            Stopwatch sw3 = Stopwatch.StartNew();
            l3 = l3.Except( toRemove ).ToList();
            sw3.Stop();

            Stopwatch sw4 = Stopwatch.StartNew();
            l4 = l4.Except( new HashSet<string>( toRemove ) ).ToList();
            sw3.Stop();


            Console.WriteLine( "L1.Len = {0}, Time taken: {1}ms", l1.Count, sw1.Elapsed.TotalMilliseconds );
            Console.WriteLine( "L2.Len = {0}, Time taken: {1}ms", l1.Count, sw2.Elapsed.TotalMilliseconds );
            Console.WriteLine( "L3.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );
            Console.WriteLine( "L4.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );

            Console.ReadKey();
        }


        private static string RandomString( int size )
        {
            StringBuilder builder = new StringBuilder();
            char ch;
            for( int i = 0; i < size; i++ )
            {
                ch = Convert.ToChar( Convert.ToInt32( Math.Floor( 26 * random.NextDouble() + 65 ) ) );
                builder.Append( ch );
            }

            return builder.ToString();
        }
    }
}

結果如下:

Be patient, generating data...
Be patient, testing...
L1.Len = 985263, Time taken: 13411.8648ms
L2.Len = 985263, Time taken: 76.4042ms
L3.Len = 985263, Time taken: 340.6933ms
L4.Len = 985263, Time taken: 340.6933ms

我們可以看到,在這種情況下最好的選擇是使用RemoveAll(HashSet)


我認為你只需要將作者列表中的項目分配給新列表即可實現此效果。

//assume oldAuthor is the old list
Author newAuthorList = (select x from oldAuthor where x.firstname!="Bob" select x).ToList();
oldAuthor = newAuthorList;
newAuthorList = null;

最好使用RemoveAll來實現這一點。

authorsList.RemoveAll((x) => x.firstname == "Bob");

簡單方案:

static void Main()
{
    List<string> myList = new List<string> { "Jason", "Bob", "Frank", "Bob" };
    myList.RemoveAll(x => x == "Bob");

    foreach (string s in myList)
    {
        //
    }
}

這是一個非常古老的問題,但我發現了一個非常簡單的方法來做到這一點:

authorsList = authorsList.Except(authors).ToList();

請注意,由於返回變量authorsListList<T> ,因此Except()返回的IEnumerable<T>必須轉換為List<T>


那麼,首先排除它們會更容易:

authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();

但是,這只會改變authorsList的值,而不是從以前的集合中刪除作者。 或者,您可以使用RemoveAll

authorsList.RemoveAll(x => x.FirstName == "Bob");

如果你真的需要基於另一個集合來做,我會使用HashSet,RemoveAll和Contains:

var setToRemove = new HashSet<Author>(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));




list