简体   繁体   中英

How to filter a list using another list in LINQ C#

The list needs to filter is having data like: '1000', '1000A', '1000B', '2000', '2000C', '2003', '2006A'

The list by which I am filtering having data like: '1000', '2000', '2003'

Expected output: 1000', '1000A', '1000B', '2000', '2000C', '2003' (output is expected like we do in SQL server LIKE operator)

Try with regex, like this:

var list1 = new List<string>{"1000", "1000A", "1000B","2000","2000A","3000BV"};
var list2 = new List<string>{"1000","2000"};

var result = list1.Where(x => list2.Any(y => Regex.IsMatch(x, $".*{y}.*"))).ToList();

Note: .* are the equivalent of % in SQL.

Suppose you are having two class like below,

public class MainClass
{
    public string ActualValue { get; set; }
}
public class FilterClass
{
    public string Description { get; set; }
}

I am loading some dummy data like this,

        List<MainClass> mainList = new List<MainClass>();
        mainList.Add(new MainClass() { ActualValue = "1000" });
        mainList.Add(new MainClass() { ActualValue = "1000A" });
        mainList.Add(new MainClass() { ActualValue = "1002F" });
        mainList.Add(new MainClass() { ActualValue = "1002A" });
        mainList.Add(new MainClass() { ActualValue = "1003" });

        List<FilterClass> filterList = new List<FilterClass>();
        filterList.Add(new FilterClass() { Description = "1003" });
        filterList.Add(new FilterClass() { Description = "1002" });

The O/P will be given as per your requirement by,

        var output1 = mainList.Where(x => filterList.Any(y => x.ActualValue.Contains(y.Description))).ToList();

you could use linq in this way :

var filterList = new List<string>(){"1000", "1000A", "1000B", "2000", "2000C", "2003", "2006A"};
var filterLikeList = new List<string>(){"1000", "2000", "2003"};

var results = filterList.Where(x=> filterLikeList.Any(y=>x.Contains(y)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM