Check if list contains element that contains a string and get that element

前端 未结 12 2496
抹茶落季
抹茶落季 2020-12-07 10:39

While searching for an answer to this question, I\'ve run into similar ones utilizing LINQ but I haven\'t been able to fully understand them (and thus, implement them), as I

12条回答
  •  执笔经年
    2020-12-07 11:29

    It is possible to combine Any, Where, First and FirstOrDefault; or just place the predicate in any of those methods depending on what is needed.

    You should probably avoid using First unless you want to have an exception thrown when no match is found. FirstOrDefault is usually the better option as long as you know it will return the type's default if no match is found (string's default is null, int is 0, bool is false, etc).

    using System.Collections.Generic;
    using System.Linq;
    
    
    bool exists;
    string firstMatch;
    IEnumerable matchingList;
    
    var myList = new List() { "foo", "bar", "foobar" };
    
    exists = myList.Any(x => x.Contains("o"));
    // exists => true
    
    firstMatch = myList.FirstOrDefault(x => x.Contains("o"));
    firstMatch = myList.First(x => x.Contains("o"));
    // firstMatch => "foo"
    
    firstMatch = myList.First(x => x.Contains("dark side"));
    // throws exception because no element contains "dark side"
    
    firstMatch = myList.FirstOrDefault(x => x.Contains("dark side"));
    // firstMatch => null
    
    matchingList = myList.Where(x => x.Contains("o")); 
    // matchingList => { "foo", "foobar" }
    

    Test this code @ https://rextester.com/TXDL57489

提交回复
热议问题