简体   繁体   中英

How to test if a list contains part of a string

I have a list of numbers and I have to check if multiple or single numbers of a string are within that list.

For example, suppose I have a list list = new List<int> { 2, 3, 4, 5, ... } with the string strSegment = "2,8" . Trying list.Contains(strSegment) clearly doesn't work. Is there any way I can do this without separating the strSegment ?

This is the code I have so far:

List<string> matchedSegs = ...;
foreach (Common.Ticket tst in lstTST)
{
    string segNums = tst.SegNums;

    var result = segNums.Split(',');
    foreach (string s in result)
    {
        if (matchedSegs.Contains(s))
        {
            blnHKFound = true;
            break;
        }
        else
        {
            strSegsNotFound += tst.strAirSegNums;
            blnHKFound = false;
        }
    }
}

Well, you can do it without splitting the strNumber, but you haven't really explained why you need that. I think splitting then using Intersect is the simplest approach and I'd recommend trying this first to see if it is good enough for you:

var result = strSegment.Split(',').Intersect(numbers);

Here's a more complete example:

string strSegment = "2,8";
List<string> numbers = new List<string> { "2", "3", "4", "5" };
var result = strSegment.Split(',').Intersect(numbers);
foreach (string number in result)
{
    Console.WriteLine("Found: " + number);
}

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