Używanie LINQ do usuwania elementów z listy
Powiedzmy, że mam zapytanie LINQ takie jak:
var authors = from x in authorsList
where x.firstname == "Bob"
select x;
Biorąc pod uwagę, że authorsList
jest typu List<Author>
, Jak mogę usunąć Author
elementy z authorsList
, które są zwracane przez zapytanie do authors
?
Lub, mówiąc inaczej, jak mogę usunąć wszystkie z pierwszego imienia równa Boba z authorsList
?
UWAGA: Jest to uproszczony przykład dla celów pytania.
15 answers
Cóż, byłoby łatwiej je wykluczyć w pierwszej kolejności:
authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();
To jednak zmieniłoby wartość authorsList
zamiast usuwać autorów z poprzedniej kolekcji. Alternatywnie można użyć RemoveAll
:
authorsList.RemoveAll(x => x.FirstName == "Bob");
Jeśli naprawdę potrzebujesz zrobić to na podstawie innej kolekcji, użyłbym HashSet, RemoveAll i zawiera:
var setToRemove = new HashSet<Author>(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-12 16:01:39
Lepiej użyć List
authorsList.RemoveAll((x) => x.firstname == "Bob");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-12 16:03:27
Jeśli naprawdę musisz usunąć elementy, to co z except ()?
Możesz usunąć na podstawie nowej listy lub usunąć w locie, zagnieżdżając 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();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-12 16:01:36
Nie możesz tego zrobić ze standardowymi operatorami LINQ, ponieważ LINQ zapewnia obsługę zapytań, a nie aktualizacji.
Ale możesz wygenerować nową listę i zastąpić starą.
var authorsList = GetAuthorList();
authorsList = authorsList.Where(a => a.FirstName != "Bob").ToList();
Lub możesz usunąć wszystkie elementy w authors
w drugim przejeździe.
var authorsList = GetAuthorList();
var authors = authorsList.Where(a => a.FirstName == "Bob").ToList();
foreach (var author in authors)
{
authorList.Remove(author);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-12 16:02:43
Proste rozwiązanie:
static void Main()
{
List<string> myList = new List<string> { "Jason", "Bob", "Frank", "Bob" };
myList.RemoveAll(x => x == "Bob");
foreach (string s in myList)
{
//
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-03 18:40:50
Błądziłem, jeśli są jakieś różnice między RemoveAll a Except i plusy używania HashSet, więc zrobiłem szybkie sprawdzenie wydajności:)
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();
}
}
}
Wyniki poniżej:
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
Jak widać, najlepszym rozwiązaniem w tym przypadku jest użycie RemoveAll( HashSet )
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-26 16:38:44
To bardzo stare pytanie, ale znalazłem na to naprawdę prosty sposób:
authorsList = authorsList.Except(authors).ToList();
Zauważ, że ponieważ zmienna zwracana authorsList
jest List<T>
, IEnumerable<T>
zwrócona przez Except()
musi zostać przekonwertowana na List<T>
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-29 02:53:38
Możesz usunąć na dwa sposoby
var output = from x in authorsList
where x.firstname != "Bob"
select x;
Lub
var authors = from x in authorsList
where x.firstname == "Bob"
select x;
var output = from x in authorsList
where !authors.Contains(x)
select x;
Miałem ten sam problem, jeśli chcesz proste wyjście oparte na warunku where, to pierwsze rozwiązanie jest lepsze.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-12 16:02:12
Powiedz, że authorsToRemove
jest IEnumerable<T>
, który zawiera elementy, które chcesz usunąć z authorsList
.
Oto kolejny bardzo prosty sposób na wykonanie zadania usuwania zadanego przez OP:
authorsList.RemoveAll(authorsToRemove.Contains);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-29 02:38:48
Myślę, że mógłbyś zrobić coś takiego
authorsList = (from a in authorsList
where !authors.Contains(a)
select a).ToList();
Chociaż myślę, że podane rozwiązania rozwiązują problem w bardziej czytelny sposób.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-12 16:41:12
Poniżej znajduje się przykład usunięcia elementu z listy.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-25 18:19:09
LINQ ma swoje początki w programowaniu funkcyjnym, które podkreśla niezmienność obiektów, więc nie zapewnia wbudowanego sposobu aktualizacji oryginalnej listy w miejscu.
Uwaga o niezmienności (zaczerpnięta z innej odpowiedzi SO):
Oto definicja niezmienności z Wikipedii (link)
" w programowaniu obiektowym i funkcyjnym obiekt niezmienny jest obiektem, którego stanu nie można zmienić po jego utworzeniu."
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-19 19:53:09
Myślę, że wystarczy przypisać elementy z listy autorów do nowej listy, aby to osiągnąć.
//assume oldAuthor is the old list
Author newAuthorList = (select x from oldAuthor where x.firstname!="Bob" select x).ToList();
oldAuthor = newAuthorList;
newAuthorList = null;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-28 05:36:21
Aby zachować płynność kodu (jeśli Optymalizacja kodu nie jest kluczowa) i musisz wykonać kilka dalszych operacji na liście:
authorsList = authorsList.Where(x => x.FirstName != "Bob").<do_some_further_Linq>;
Lub
authorsList = authorsList.Where(x => !setToRemove.Contains(x)).<do_some_further_Linq>;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-15 13:48:45
Jest bardzo proste:
authorsList.RemoveAll((x) => x.firstname == "Bob");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-24 12:06:15