user584018
user584018

Reputation: 11304

Compare string within list of string using Ignore Symbol without foreach

I am trying to compare a string within a list of string where I would like to use "IgnoreSymbols" compare option. Is there a way without "foreach" of list of string?

List<string> lstString = new List<string> { "Hello [T]", "XYA" };
string str = "Hello (T)";

var Y = String.Compare(str, lstString.Any(e => e.ToString()), CultureInfo.InvariantCulture, CompareOptions.IgnoreSymbols);

if (Y == 0)
{
    Console.WriteLine("equal");
}

Upvotes: 0

Views: 167

Answers (4)

rmjoia
rmjoia

Reputation: 980

Is this what you're looking for? You can use projection and do whatever you want.

List<string> lstString = new List<string> { "Hello [T]", "XYA" };
string str = "Hello (T)";

var Y = lstString.Select(e => String.Compare(str, e, CultureInfo.InvariantCulture, CompareOptions.IgnoreSymbols));

if (Y.Contains(0))
{
    Console.WriteLine("equal");
}

Or

List<string> lstString = new List<string> { "Hello [T]", "XYA" };
string str = "Hello (T)";

var Y = lstString.Any(e => String.Compare(str, e, CultureInfo.InvariantCulture, CompareOptions.IgnoreSymbols) == 0);

if (Y)
{
    Console.WriteLine("equal");
}

Edited with @Bojan B suggestion :) thanks :)

Upvotes: 2

Ipsit Gaur
Ipsit Gaur

Reputation: 2927

You can use this -

var result = lstString.Any(x => Regex.Replace(x, @"[^0-9a-zA-Z]+", "").Equals(Regex.Replace(str, @"[^0-9a-zA-Z]+", "")));
if(result) 
{
  // Write code here
}

But looking in detail I think using foreach or writing will result in same execution time if you are breaking from foreach loop.

Upvotes: 1

Bojan B
Bojan B

Reputation: 2111

You can use LINQ, in general you are close with your idea, you just need to switch Any with String.Compare.

Like this:

var y = lstString.Any(e => string.Compare(str, e, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.CompareOptions.IgnoreSymbols) == 0);

Upvotes: 4

Zohar Peled
Zohar Peled

Reputation: 82474

From what I understand, you want to know if the list contains a string that's equal to the search string (str), ignoring symbols.
You can use Any:

var lstString = new List<string> { "Hello [T]", "XYA" };
var str = "Hello (T)";

var Y = lstString.Any(s => String.Compare(s, str, CultureInfo.InvariantCulture, CompareOptions.IgnoreSymbols) == 0);

if (Y)
{
    Console.WriteLine("Found");
}

Upvotes: 4

Related Questions