Usinq Linq to select items that is in a semi-comma separated string?

后端 未结 3 1387
孤城傲影
孤城傲影 2020-12-18 08:23

I have a string with semi-comma separated names:

string names = \"Jane;Harry\";

I also have a list of customer objects:

pub         


        
相关标签:
3条回答
  • 2020-12-18 08:50

    It Will Helps

    string allid = "11,12,13,14,15,16";
    string[] arrid = allid.Split(',');
    var data = context.MyModels.Where(x => arrid.Contains(x.ProjectId.ToString()));
    
    0 讨论(0)
  • 2020-12-18 08:55

    Well, you should really split the string up to start with - otherwise you'll get a match for "Jane" even if the list is "Janet;Harry".

    You could do:

    string[] validNames = names.Split(';');
    var query = customers.Where(c => validNames.Contains(c.FirstName));
    

    Another option is to use a HashSet, which will perform a lot better when the list is very large:

    HashSet<string> validNames = new HashSet<string>(names.Split(';'));
    var query = customers.Where(c => validNames.Contains(c.FirstName));
    

    I've used dot notation here instead of a query expression because it's simpler when you're just applying a clause or two. As a query expression though, it would be:

    var query = from c in customers
                where validNames.Contains(c.FirstName)
                select c;
    
    0 讨论(0)
  • 2020-12-18 08:55

    You can try this.

    List firstnames = names.Split(';').ToList();

    var query = from c in customers
                where firstnames.Contains(c.FirstName) 
                select c ;    
    
    0 讨论(0)
提交回复
热议问题