C# parse & compare huge list/string - c#

I have 2 giant lists (over 2000 each)
And I want to parse & compare them.
What the list looks like:
zone "exampledomain.com" {
zone "exampledomain2.com" {
zone "exampledomain3.com" {
zone "exampledomain4.com" {
zone "exampledomain5.com" {
zone "exampledomain6.com" {
zone "exampledomain7.com" {
What the other list looks like:
zone "exampledomain.com" {
zone "exampledomain3.com" {
zone "exampledomain5.com" {
zone "exampledomain7.com" {
Both lists have this same format of zone "____" {
I want to parse so that I can compare the domains and then get the difference of domains so I know what the other one is missing, they should both have the same results.
I have come across this code:
static void Main(string[] args)
{
string s1 = "i have a car a car";
string s2 = "i have a new car bmw";
List<string> diff;
IEnumerable<string> set1 = s1.Split(' ').Distinct();
IEnumerable<string> set2 = s2.Split(' ').Distinct();
if (set2.Count() > set1.Count())
{
diff = set2.Except(set1).ToList();
}
else
{
diff = set1.Except(set2).ToList();
}
}
But I am wondering what would be the best way to do it considering I have over 2000 lines in each list.

The example you give will only show list 1 with the items from list 2 removed. If you also want what is in list 2 that isn't in list 1 you will have to do two queries
var difference1 = list1.Except(list2);
var difference2 = list2.Except(list1);
I'm not sure what code is involved when Except is executed, but if you'd like to see an implementation of how to generate two lists containing differences then here is one solution:
static void Differerence(
IEnumerable<string> source1, IEnumerable<string> source2,
out List<string> difference1, out List<string> difference2)
{
//Move the data from the sources into ordered queues
var sourceValues1 = new Queue<string>(source1.OrderBy(x => x));
var sourceValues2 = new Queue<string>(source2.OrderBy(x => x));
difference1 = new List<string>();
difference2 = new List<string>();
while(sourceValues1.Count > 0 && sourceValues2.Count > 0)
{
string value1 = sourceValues1.Peek();
string value2 = sourceValues2.Peek();
switch (string.Compare(value1, value2))
{
//If they match then don't add difference to either list
case 0:
sourceValues1.Dequeue();
sourceValues2.Dequeue();
break;
//The left queue has the lowest value, record that and move on
case -1:
difference1.Add(value1);
sourceValues1.Dequeue();
break;
//The right queue has the lowest value, record that and move on
case 1:
difference2.Add(value2);
sourceValues2.Dequeue();
break;
}
}
//At least one of the queues is empty, so everything left in the other queue
difference1.AddRange(sourceValues1);
difference2.AddRange(sourceValues2);
}
I don't know how LINQ could possibly do it any faster, but my routine will deal with duplicates entries like the value "1" in the following example, whereas LINQ won't. So keep that in mind when choosing which to use rather than just the difference in speed.
static void Main(string[] args)
{
var list1 = new string[] { "1", "1", "3", "5", "7", "9" };
var list2 = new string[] { "1", "2", "4", "6", "9", "10" };
var difference1 = list1.Except(list2);
var difference2 = list2.Except(list1);
List<string> differenceX1;
List<string> differenceX2;
Differerence(list1, list2, out differenceX1, out differenceX2);
}
It's easy to combine the two results into one if you need to
var allDifferences = differenceX1.Union(differenceX2);

HashSets are used for lists of unique elements:
https://msdn.microsoft.com/en-us/library/bb359438(v=vs.110).aspx
HashSet<string> uniqueStrings = new HashSet<string>();
foreach (string s1 in list1)
{
uniqueStrings.Add(s1);
}
foreach (string s2 in list2)
{
uniqueStrings.Add(s2);
}

Related

convert the strings in my list to a list c#

i'm quite new to this, i already did a little c# in unity, but never really in VS.
I have a txt file that looks approximatively like this :
monday;8;server1,server2,server3
tuesday;9;server3,server4
wedneday;8;server1,server2,server4
i splitted this into 3 list, one with the day (monday)... one with the hour (8)... and one with the servers(server1,server2,server3), but i would like to convert this server string into unique lists,
for example i would like a list1 to contain all servers to of monday (server1,server2,server3), a list2 to contain all servers of tuesday (server3,server4).
These servers names are splitted with a comma, and i would like to split every string into a
unique list
i know i was not very clear, please ask for any specifications
List<string> plages_horaires_ouverture = File.ReadAllLines(#"file.txt").ToList();
foreach (var fileLine in plages_horaires_ouverture)
{
var splitLignes = fileLine.Split(new[] { ";" }, StringSplitOptions.None);
listeJoursOuverture.Add(splitLignes[0]);
listeHeuresOuverture.Add(splitLignes[1]);
listeServeursOuverture.Add(splitLignes[2]);
}
this code splits the txt file into 3 separate lists containing strings, and now i would like to convert every element (string) of the list "listeServeursOuverture" (sorry for the french name) into a unique list. Every element in this list looks like this "server1,server2,server4" or "server2,server3" and is separated with a comma
Any ideas? I tried many things but none worked, this question is certainly stupid, and im sorry for that
Leno
Use List.AddRange():
List<String> servers = new List<String>();
servers.AddRange(splitLignes[2].Split(new[] { "," }, StringSplitOptions.None));
I'd use a dictionary here:
List<string> plages_horaires_ouverture = File.ReadAllLines(#"file.txt").ToList();
Dictionary<KeyValuePair<string, string>,List<string>> servers = new Dictionary<KeyValuePair<string, string>,List<string>>
foreach (var fileLine in plages_horaires_ouverture)
{
var splitLignes = fileLine.Split(new[] { ";" }, StringSplitOptions.None);
KeyValuePair<string, string> key = new KeyValuePair<string, string>(splitLignes[0], splitLignes[1]);
List<string> serversForDay = splitLignes[2].Split(new[] { "," }, StringSplitOptions.None);
servers.Add(key, serversForDay);
}
Instead of spreading your data into different Lists, I'd have one List (or at least some kind of DataStructure. You may later find a Dictionary helpful, maybe).
In that List, I'd have instances of a Model class like for example this one:
public class MyModel
{
public string Day {get; set;}
public int Hour {get; set;}
public List<string> Servers {get; set;} = new List<string>();
}
Then you can look up the Server Lists by Day as you want if I read the question correctly.
Populating may go something like this:
foreach (var fileLine in plages_horaires_ouverture)
{
var splitLignes = fileLine.Split(new[] { ";" }, StringSplitOptions.None);
var model = new MyModel{
Day = splitLignes[0],
Hour = int.Parse(splitLignes[1].Trim())
};
model.Servers.AddRange(splitLignes[2].Split(new[] { "," }, StringSplitOptions.None));
listeOverture.Add(model);
// don't need these anymore.
// listeJoursOuverture.Add(splitLignes[0]);
// listeHeuresOuverture.Add(splitLignes[1]);
// listeServeursOuverture.Add(splitLignes[2]);
}
You can edit the names and the types as needed. Make a class object to sort the data as you like, then make a method that returns a list of that class. This is more clear for you when you need to deal with your code later.
public List<DataModel> GetListFromData()
{
List<string> plages_horaires_ouverture = File.ReadAllLines( #"file.txt" ).ToList();
List<DataModel> list = new List<Dd>();
foreach ( var fileLine in plages_horaires_ouverture )
{
var splitLignes = fileLine.Split( ";" , StringSplitOptions.None );
List<string> d = splitLignes[0].Split( "," ).ToList();
List<string> h =splitLignes[1].Split( "," ).ToList();
List<string> s =splitLignes[2].Split( "," ).ToList();
list.Add( new DataModel( d , h[0] , s ) );
}
return list;
}
class DataModel
{
public DataModel( List<string> days,string hour , List<string> servers )
{
Hour = hour;
Days = days;
Servers = servers;
}
public string Hour { get; set; }
public List<string> Days { get; set; }
public List<string> Servers { get; set; }
}

How to get every possible combination base on the ranges in brackets?

Looking for the best way to take something like 1[a-C]3[1-6]07[R,E-G] and have it output a log that would look like the following — basically every possible combination base on the ranges in brackets.
1a3107R
1a3107E
1a3107F
1a3107G
1b3107R
1b3107E
1b3107F
1b3107G
1c3107R
1c3107E
1c3107F
1c3107G
all the way to 1C3607G.
Sorry for not being more technical about what I looking for, just not sure on the correct terms to explain.
Normally what we'd do to get all combinations is to put all our ranges into arrays, then use nested loops to loop through each array, and create a new item in the inner loop that gets added to our results.
But in order to do that here, we'd first need to write a method that can parse your range string and return a list of char values defined by the range. I've written a rudimentary one here, which works with your sample input but should have some validation added to ensure the input string is in the proper format:
public static List<char> GetRange(string input)
{
input = input.Replace("[", "").Replace("]", "");
var parts = input.Split(',');
var range = new List<char>();
foreach (var part in parts)
{
var ends = part.Split('-');
if (ends.Length == 1)
{
range.Add(ends[0][0]);
}
else if (char.IsDigit(ends[0][0]))
{
var start = Convert.ToInt32(ends[0][0]);
var end = Convert.ToInt32(ends[1][0]);
var count = end - start + 1;
range.AddRange(Enumerable.Range(start, count).Select(c => (char) c));
}
else
{
var start = (int) ends[0][0];
var last = (int) ends[1][0];
var end = last < start ? 'z' : last;
range.AddRange(Enumerable.Range(start, end - start + 1)
.Select(c => (char) c));
if (last < start)
{
range.AddRange(Enumerable.Range('A', last - 'A' + 1)
.Select(c => (char) c));
}
}
}
return range;
}
Now that we can get a range of values from a string like "[a-C]", we need a way to create nested loops for each range, and to build our list of values based on the input string.
One way to do this is to replace our input string with one that contains placeholders for each range, and then we can create a loop for each range, and on each iteration we can replace the placeholder for that range with a character from the range.
So we'll take an input like this: "1[a-C]3[1-6]07[R,E-G]", and turn it into this: "1{0}3{1}07{2}". Now we can create loops where we take the characters from the first range and create a new string for each one of them, replacing the {0} with the character. Then, for each one of those strings, we iterate over the second range and create a new string that replaces the {1} placeholder with a character from the second range, and so on and so on until we've created new strings for every possible combination.
public static List<string> GetCombinatins(string input)
{
// Sample input = "1[a-C]3[1-6]07[R,E-G]"
var inputWithPlaceholders = string.Empty; // This will become "1{0}3{1}07{2}"
var placeholder = 0;
var ranges = new List<List<char>>();
for (int i = 0; i < input.Length; i++)
{
// We've found a range start, so replace this with our
// placeholder '{n}' and add the range to our list of ranges
if (input[i] == '[')
{
inputWithPlaceholders += $"{{{placeholder++}}}";
var rangeEndIndex = input.IndexOf("]", i);
ranges.Add(GetRange(input.Substring(i, rangeEndIndex - i)));
i = rangeEndIndex;
}
else
{
inputWithPlaceholders += input[i];
}
}
if (ranges.Count == 0) return new List<string> {input};
// Add strings for the first range
var values = ranges.First().Select(chr =>
inputWithPlaceholders.Replace("{0}", chr.ToString())).ToList();
// Then continually add all combinations of other ranges
for (int i = 1; i < ranges.Count; i++)
{
values = values.SelectMany(value =>
ranges[i].Select(chr =>
value.Replace($"{{{i}}}", chr.ToString()))).ToList();
}
return values;
}
Now with these methods out of the way, we can create output of all our ranges quite easily:
static void Main()
{
Console.WriteLine(string.Join(", ", GetCombinatins("1[a-C]3[1-6]07[R,E-G]")));
GetKeyFromUser("\nPress any key to exit...");
}
Output
I would approach this problem in three stages. The first stage is to transform the source string to an IEnumerable of IEnumerable<string>.
static IEnumerable<IEnumerable<string>> ParseSourceToEnumerables(string source);
For example the source "1[A-C]3[1-6]07[R,E-G]" should be transformed to the 6 enumerables below:
"1"
"A", "B", "C"
"3"
"1", "2", "3", "4", "5", "6"
"07"
"R", "E", "F", "G"
Each literal inside the source has been transformed to an IEnumerable<string> containing a single string.
The second stage would be to create the Cartesian product of these enumerables.
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
IEnumerable<IEnumerable<T>> sequences)
The final (and easiest) stage would be to concatenate each one of the inner IEnumerable<string> of the Cartesian product to a single string. For example
the sequence "1", "A", "3", "1", "07", "R" to the string "1A3107R"
The hardest stage is the first one, because it involves parsing. Below is a partial implementation:
static IEnumerable<IEnumerable<string>> ParseSourceToEnumerables(string source)
{
var matches = Regex.Matches(source, #"\[(.*?)\]", RegexOptions.Singleline);
int previousIndex = 0;
foreach (Match match in matches)
{
var previousLiteral = source.Substring(
previousIndex, match.Index - previousIndex);
if (previousLiteral.Length > 0)
yield return Enumerable.Repeat(previousLiteral, 1);
yield return SinglePatternToEnumerable(match.Groups[1].Value);
previousIndex = match.Index + match.Length;
}
var lastLiteral = source.Substring(previousIndex, source.Length - previousIndex);
if (lastLiteral.Length > 0) yield return Enumerable.Repeat(lastLiteral, 1);
}
static IEnumerable<string> SinglePatternToEnumerable(string pattern)
{
// TODO
// Should transform the pattern "X,A-C,YZ"
// to the sequence ["X", "A", "B", "C", "YZ"]
}
The second stage is hard too, but solved. I just grabbed the implementation from Eric Lippert's blog.
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
accumulator.SelectMany(_ => sequence,
(accseq, item) => accseq.Append(item)) // .NET Framework 4.7.1
);
}
The final stage is just a call to String.Join.
var source = "1[A-C]3[1-6]07[R,E-G]";
var enumerables = ParseSourceToEnumerables(source);
var combinations = CartesianProduct(enumerables);
foreach (var combination in combinations)
{
Console.WriteLine($"Combination: {String.Join("", combination)}");
}

Create two random lists from one list

I want to take a List of strings with around 12 objects and split it into two List of strings but completely randomise it.
Example of List:
List 1:
EXAMPLE 1
EXAMPLE 2
EXAMPLE 3
EXAMPLE 4
EXAMPLE 5
EXAMPLE 6
EXAMPLE 7
EXAMPLE 8
Apply some logic here...
Result gives me two lists:
List 1:
EXAMPLE 5
EXAMPLE 6
EXAMPLE 1
EXAMPLE 8
List 2:
EXAMPLE 2
EXAMPLE 3
EXAMPLE 4
EXAMPLE 7
I'm a newbie to C# MVC, so I've found some answers on Stack but none have been able to answer my question.
Edit:
What I've tried so far gives me one random member of the team. I want to now expand on this and create the two lists as mentioned above.
[HttpPost]
public ActionResult Result(Models.TeamGenerator model)
{
var FormNames = model.Names;
string[] lines = FormNames.Split(
new[] { Environment.NewLine },
StringSplitOptions.None);
List<string> listOfLines = new List<string>();
foreach (var i in lines)
{
listOfLines.Add(i);
}
string[] result1 = listOfLines.Where(item => item != string.Empty).ToArray();
Random genRandoms = new Random();
int aRandomTeam = genRandoms.Next(listOfLines.Count);
string currName = listOfLines[aRandomTeam];
return View();
}
*EDIT** Thanks for the solution! I've now got my application working and managed to publish it to the web, https://www.teamgenerator.online.
Create an array of bools the same size as the list of strings.
Fill one half of the array of bools with true, the other half with false.
Shuffle the array of bools.
Iterate through the list of strings. For each element, if the corresponding element in the bool array is true, include that element in the first list; otherwise include it in the second list.
This approach keeps the items in the same order as they were in the original array, if that is important. (If not, just shuffle the entire array of strings and take the first half and the second half).
Sample code:
using System;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
var strings = Enumerable.Range(1, 20).Select(i => i.ToString()).ToList();
var rng = new Random();
int n = strings.Count;
var include = // Create array of bools where half the elements are true and half are false
Enumerable.Repeat(true, n/2) // First half is true
.Concat(Enumerable.Repeat(false, n-n/2)) // Second half is false
.OrderBy(_ => rng.Next()) // Shuffle
.ToArray();
var list1 = strings.Where((s, i) => include[i]).ToList(); // Take elements where `include[index]` is true
var list2 = strings.Where((s, i) => !include[i]).ToList(); // Take elements where `include[index]` is false
Console.WriteLine(string.Join(", ", list1));
Console.WriteLine(string.Join(", ", list2));
}
}
}
Here's a completely different approach that uses a modified version of a standard algorithm for selecting K items from N items (in this case, K = N/2):
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
var strings = Enumerable.Range(1, 20).Select(n => n.ToString()).ToList();
var list1 = new List<string>();
var list2 = new List<string>();
var rng = new Random();
int available = strings.Count;
int remaining = available / 2;
foreach (var s in strings)
{
if (rng.NextDouble() < remaining / (double) available)
{
list1.Add(s);
--remaining;
}
else
{
list2.Add(s);
}
--available;
}
Console.WriteLine(string.Join(", ", list1));
Console.WriteLine(string.Join(", ", list2));
}
}
}
This approach is much more performant than my first solution, but since your list is only about 12 items long, this is hardly important for your problem.
You're currently only generating one random number and getting one value. What you need to do is put that into a loop that is run half as many times as there are items in the list.
var genRandoms = new Random();
var numberRequired = listOfLines.Count/2;
var output = new List<string>();
for (var i=0; i<numberRequired; i++)
{
var aRandomTeam = genRandoms.Next(listOfLines.Count);
output.Add(listOfLines[aRandomTeam]);
listOfLines.RemoveAt(aRandomTeam);
}
Also, this bit at the beginning:
string[] lines = FormNames.Split(
new[] { Environment.NewLine },
StringSplitOptions.None);
List<string> listOfLines = new List<string>();
foreach (var i in lines)
{
listOfLines.Add(i);
}
string[] result1 = listOfLines.Where(item => item != string.Empty).ToArray();
Can be rewritten as:
var listOfLines = FormNames.Split(
new[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries).ToList();
Removing the empty items as part of the split, and using a built-in method to convert it to a list.
First, try to shuffle the list using the Random function
static class MyExtensions
{
private static Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
then split the list into two using Linq
static void Main(String[] args)
{
List<string> examples = new List<string>();
for(int i=1;i<=12;i++)
{
examples.Add($"Example {i}");
}
examples.Shuffle();
var firstlist = examples.Take(examples.ToArray().Length / 2).ToArray();
Console.WriteLine(String.Join(", ", firstlist));
var secondlist = examples.Skip(examples.ToArray().Length / 2).ToArray();
Console.WriteLine(String.Join(", ", secondlist));
Console.ReadLine();
}
the output looks like this
Example 6, Example 8, Example 3, Example 9, Example 5, Example 2
Example 10, Example 11, Example 4, Example 7, Example 12, Example 1
So I wrote an example in a console app, but the concept works just the same... See comments in code block below
Sample List
var fullList = new List<string>()
{
"ITEM 01", "ITEM 02", "ITEM 03", "ITEM 04", "ITEM 05", "ITEM 06",
"ITEM 07", "ITEM 08", "ITEM 09", "ITEM 10", "ITEM 11", "ITEM 12"
};
Initialize Two Lists to Split Values
var list1 = new List<string>();
var list2 = new List<string>();
Creating Two Random Lists
// Initialize one Random object to use throughout the loop
var random = new Random();
// Note: Start at count and count down because we will alter the count of the list
// so counting up is going to mess up. Ex: Count = 4, Remove 1 (Count = 3), Loop won't go to 4
for(int i = fullList.Count; i > 0; i--)
{
// Pull random index
var randomIndex = random.Next(fullList.Count);
// Pull item at random index
var listItem = fullList[randomIndex];
// If i is even, put it in list 1, else put it in list 2.
// You could do whatever you need to choose a list to put it
if (i % 2 == 0)
list1.Add(listItem);
else
list2.Add(listItem);
// Remove random item from the full list so it doesn't get chosen again
fullList.RemoveAt(randomIndex);
}
Results
Console.WriteLine("LIST 1");
Console.WriteLine(string.Join(Environment.NewLine, list1));
Console.WriteLine();
Console.WriteLine("LIST 2");
Console.WriteLine(string.Join(Environment.NewLine, list2));
-----------------------
LIST 1
ITEM 05
ITEM 04
ITEM 12
ITEM 11
ITEM 08
ITEM 01
LIST 2
ITEM 02
ITEM 03
ITEM 09
ITEM 06
ITEM 10
ITEM 07
Here's a simple solution that falls in line with how you were attempting to solve the problem.
The main logic is as followed:
while there are still items in the master list:
choose a random number [0,list.count) as the current target index
choose a random number [0,1] as the current target list to add to
add the item chosen randomly to the randomly selected list
remove the item chosen from the master list
Here's the code:
var random = new Random();
var list = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var newList1 = new List<string>();
var newList2 = new List<string>();
while(list.Count > 0)
{
//choose the index randomly
int index = random.Next(list.Count);
//get the item at the randomly chosen index
string curItem = list[index];
//choose the list randomly(1==newList1, 2==newList2)
int listChoice = random.Next(2);
//Add the item to the correct list
if(listChoice == 1)
{
newList1.Add(curItem);
}
else
{
newList2.Add(curItem);
}
//finally, remove the element from the string
list.RemoveAt(index);
}

Is there an equivalent of bulk contains?

Is there some utility to check whether a sequence contains multiple elements instead of using Contains repeatedly?
List<string> containter = new List<string>();
for (int i = 0; i < 10; i++)
{
containter.Add("string #" + i);
}
if (containter.Contains("string #2") && //Is it possible to replace this with one call passing two strings to improve efficiency
containter.Contains("string #6"))
{
//Do Something
}
According to the updated question, I've modified my answer:
List<string> containter = new List<string>();
for (int i = 0; i < 10; i++)
{
containter.Add("string #" + i);
}
//define a checklist
List<string> checkList = new List<string> { "string #2", "string #6" };
//we're in, if every item in checkList is present in container
if (!checkList.Except(containter).Any())
{
Console.WriteLine("true");
}
Still you may use Any. But in this context it would be nice to use Except method.
If every item in checkList is present in the container the resulting sequence would contain no elements, so Any should return false.
I am assuming you want to compare two sequences, and want to know if one sequence contains all of the elements in another sequence.
var outer = new List<String>() { "1", "2", "3" };
var inner = new List<String>() { "1", "2" };
bool outerContainsAllInnerElements = inner.TrueForAll(i => outer.Contains(i));
Alternatively, you could use Intersect(), but that will project your items into a new sequence when you attempt to get its count. If that's what you want, great, but if you don't need to know which elements intersect, then TrueForAll() would save that overhead.
var outer = new List<String>() { "1", "2", "3" };
var inner = new List<String>() { "1", "2" };
var elementsInBoth = outer.Intersect(inner);
bool outerContainsAllInnerElements = (elementsInBoth.Count() == inner.Count());
Any:
string s = "I am a string";
string[] check = { "is", "my" };
Console.WriteLine(check.Any(x => s.Contains(x))); // False
s = "This is a string";
Console.WriteLine(check.Any(x => s.Contains(x))); // True
s = "my string";
Console.WriteLine(check.Any(x => s.Contains(x))); // True

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);
}

Categories