how to remove from list using Lambda syntax

前端 未结 2 1668
无人及你
无人及你 2021-02-12 10:06

Given:

List names = new List(); //list full of names

public void RemoveName(string name) {
   List n = names.Where(x => x         


        
相关标签:
2条回答
  • 2021-02-12 10:29
    var n = names.SingleOrDefault(x => x.UserName == name)
    if(n != null && n.UserName.length > 0)
    {
     names.Remove(n);
    }
    

    OR

    var n= names.Where(x => x.UserName == name).First();
    names.Remove(n)
    
    0 讨论(0)
  • 2021-02-12 10:38
    names.RemoveAll(x => x.UserName == name);
    

    Note here that all the lambda syntax does is provide a Predicate<T>; lambda syntax is entirely unrelated to what it ends up doing with the lambda.

    Or for a single match (see comments):

    var found = names.Find(x => x.UserName == name);
    if(found != null) names.Remove(found);
    

    or:

    var index = names.FindIndex(x => x.UserName == name);
    if(index >= 0) names.RemoveAt(index);
    
    0 讨论(0)
提交回复
热议问题