Answers:
好吧,首先将它们排除会更容易:
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));
Contains
检查快速,并确保您只评估一次序列。
List<T>
,可以使用它。
authorsList = authorsList.Where(x => x.FirstName != "Bob")
最好使用List <T> .RemoveAll完成此操作。
authorsList.RemoveAll((x) => x.firstname == "Bob");
如果您确实需要删除项目,那么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();
Except()
这是进入LINQ语句中间的唯一方法。IEnumerable
没有也Remove()
没有RemoveAll()
。
您不能使用标准LINQ运算符来执行此操作,因为LINQ提供查询而不是更新支持。
但是您可以生成一个新列表并替换旧列表。
var authorsList = GetAuthorList();
authorsList = authorsList.Where(a => a.FirstName != "Bob").ToList();
或者,您可以authors
在第二遍中删除所有项目。
var authorsList = GetAuthorList();
var authors = authorsList.Where(a => a.FirstName == "Bob").ToList();
foreach (var author in authors)
{
authorList.Remove(author);
}
RemoveAll()
不是LINQ运算符。
简单的解决方案:
static void Main()
{
List<string> myList = new List<string> { "Jason", "Bob", "Frank", "Bob" };
myList.RemoveAll(x => x == "Bob");
foreach (string s in myList)
{
//
}
}
我想知道和之间的区别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)
l2.RemoveAll( new HashSet<string>( toRemove ).Contains );
仅供参考,编译效果很好
这是一个非常老的问题,但是我发现了一种非常简单的方法:
authorsList = authorsList.Except(authors).ToList();
请注意,由于return变量authorsList
是a List<T>
,因此必须将return IEnumerable<T>
by Except()
转换为a List<T>
。
您可以通过两种方式删除
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;
我有同样的问题,如果您想根据where条件进行简单输出,那么第一个解决方案更好。
下面是从列表中删除元素的示例。
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
LINQ起源于函数式编程,该函数强调对象的不变性,因此它没有提供内置方法来就地更新原始列表。
关于不变性的注释(摘自另一个SO答案):
这是Wikipedia不变性的定义。
在面向对象的函数式编程中,不可变对象是创建后状态无法更改的对象。
为了保持代码流畅(如果代码优化不是很关键),您需要对列表进行一些进一步的操作:
authorsList = authorsList.Where(x => x.FirstName != "Bob").<do_some_further_Linq>;
要么
authorsList = authorsList.Where(x => !setToRemove.Contains(x)).<do_some_further_Linq>;