Get index in array if string exists in it using C# - c#

I'm using this code to check if the string (oCode/ originalCode) exists in the array (the string is written by user):
if (dic.cs.Any(code.Contains)) //dic.cs is in another class (cs is the array), the code variable is what I look for in the array
{
//I want to get the string was found in the array with the "Contains" function
}
I want to get the string that was found in the array with the Contains() function.

If it's possible to have multiple matches, then use this:
var foundCodes = dic.cs.Where(code.Contains);
foreach(var foundCode in foundCodes)
{
}
Otherwise:
var foundCode = dic.cs.FirstOrDefault(code.Contains);
if (!String.IsNullOrEmpty(foundCode))
{
}

You need a lambda expression in the Any method:
https://code.msdn.microsoft.com/LINQ-Quantifiers-f00e7e3e#AnySimple
var answer = yourArray.any(a => a == "WhatYouAreLookingFor");
if answer is true, then you found it.

I believe what you need is the array IndexOf method. https://msdn.microsoft.com/en-us/library/system.array.indexof(v=vs.110).aspx

Related

How can we match string contains any value of array in C# w/o using loop?

How can we match string contains any value of array in C# w/o using loop?
For example:
string[] abc= [val1,val2,val3] .
string xyz= "demo string to check if it contains any value in abc array that is val2";
I want to check if any value of array abc exists in string xyz w/o using loop
one aproach may be linq
string[] abc = { "abc", "def", "xyz" };
string xyz = "demo string to check if it contains any value in abc array that is val2";
bool result = abc.Any(xyz.Contains); //true
but internal linq and contains uses loop - so i think there is no possible solution without a loop.
To search from/in a collection (read array), you need to use loops/iteration because collection is involved.
Even if you do not write a loop and write some syntactic sugar code, in the background it will use LOOP/ITERATION.
As others answered you can use LINQ or something but it will iterate over your collection.
There is already a contains function. you may use it like this
bool result=abc.Contains("walue to be checked");
Alternate way is by using LINQ
but both the method use internal loops.
you can check as :
string[] arr = { "abc", "bcd", "cde" };
if (arr.Contains("abc"))
{
Console.WriteLine("Found");
}
else
{
Console.WriteLine("Not Found");
}
For faster way you can use Array.IndexOf Method:
int pos = Array.IndexOf(arr, "abc");
if (pos > -1)
{
// the array contains the string and the pos variable
// will have its position in the array
}

XNA list elementAt

I'm using a List of platforms. I need to do something like platforms.get(i).X
I found something like that, it's called elementAt, but it only allows you to do platforms.elementAt(i).draw(). How do I check the variables of a specific object in the list?
You can access list elements with array index notation.
int x = platforms[i].X;
You could use a delegate for something like yourlist.Exists
if (stringlist.Exists(
delegate(String s)
{
return (s == "what you want to be found"); //this returns true if it is found.
}
))
{
//What you want to do if it is found.
}
Lookup more info about using lists and delegates and you should stumble on a way you could use this to solve your problem.

send a String array as parameter to a function

I have a function in a class called Function, like below:
public int SearchedRecords(String [] recs)
{
int counter = 0;
String pat = "-----";
String[] records = recs;
foreach (String line in records)
{
if (line.Contains(pat) == true)
{
counter++;
}
}
return counter;
}
And I am calling this method from my main class this way:
String [] file = File.ReadAllLines("C:/Users.../results.txt");
int counter = Function.SearchedRecords( []file);
But I get an error saying:
;expected
What is wrong?
Another question: The function above is counting from a file all the lines with the pattern ----- in them (even if with more dashes, or if the line has some chars before or after the dashes). Am I right?
It's something like the patterns in Java so maybe there is an other way.
Can you enlighten me?
Remove the [] from your parameter.
e.g.
int counter = Function.SearchedRecords(file);
And yes, your assumption about the behavior of the Contains method is correct - you'll match any line containing five consecutive dashes, regardless of what characters are before or after them.
If you want to parse for exactly five dashes, with nothing before or after them I suggest looking into the RegEx class (regular expressions).
Change
int counter = Function.SearchedRecords( []file);
to
int counter = Function.SearchedRecords(file);
and yes, this will work, for that string.
However Contains is case sensitive, if you were matching on a name, or another string with alphabetic characters, the case would have to be identical to match e.g. line.Contains("Binary Worrier") will not match a string "Hello binary worrier".
Also, reading the entire file into memory is fine if you know that the file will always be small, this method gets less efficient the larger the file.
Better to always use something like System.IO.StreamReader or System.IO.File.ReadLines (available in .Net 4 and later), these allow you to consume the file one line at a time. e.g.
using (var reader = new System.IO.StreamReader("MyFile.txt"))
{
while(!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line.Contains(pattern))
counter++;
}
}
Change it to
int counter = Function.SearchedRecords(file);
Remove '[]' from a method call. Yes, your function seems to count what you want.
First of all you need to create an instance of function class and then run the function. Hope following code helps
Function fb = new Function();
int counter = fb.SearchedRecords(file);
Right now, you are using SearchRecords as an static function of a static class which doesn't require instantiation.
You can do this in a shorter way using LINQ:
int counter = file.Count(line => line.Contains("-----"));

How to use string.Contains for list of values

I have the following xmlnode (string) whose value would be of few given type i.e:
"Ansi_nulls","Encrypted","Quoted_identifer" etc.
I want to test the xmlnode using xmlNode.Contains ("xxx","yyy") ..
What is the correct syntax ?
If you are testing the full (complete) value of the node, you can do it by reversing the call; check that a list of known values contains your current node value:
new[]{"Ansi_nulls","Encrypted","Quoted_identifer", ...}.Contains(xmlNode);
I would create an extension method using sehes solution:
public static bool Contains(this string source, params string[] values)
{
return values.Any(value => source.Contains(value));
}
That way you can call:
xmlNode.Contains("string", "something else");
Contains takes a string to test for.
One way to solve your problem would be to use a simple regular expression
using System.Text.RegularExpressions;
if (Regex.IsMatch(nodevalue, "(Ansi_nulls|Encrypted|Quoted_identifer)")...
if (new[] {"xxx","yyy"}.Any(n => xmlNode.Contains(n)))
A simple if statement will work:
if (xmlNode.Contains("xxx") && xmlNode.Contains("yyy"))
{
// your work
}

C# Array contains partial

How to find whether a string array contains some part of string?
I have array like this
String[] stringArray = new [] { "abc#gmail.com", "cde#yahoo.com", "#gmail.com" };
string str = "coure06#gmail.com"
if (stringArray.Any(x => x.Contains(str)))
{
//this if condition is never true
}
i want to run this if block when str contains a string thats completely or part of any of array's Item.
Assuming you've got LINQ available:
bool partialMatch = stringArray.Any(x => str.Contains(x));
Even without LINQ it's easy:
bool partialMatch = Array.Exists(stringArray, x => str.Contains(x));
or using C# 2:
bool partialMatch = Array.Exists(stringArray,
delegate(string x) { return str.Contains(x)); });
If you're using C# 1 then you probably have to do it the hard way :)
If you're looking for if a particular string in your array contains just "#gmail.com" instead of "abc#gmail.com" you have a couple of options.
On the input side, there are a variety of questions here on SO which will point you in the direction you need to go to validate that your input is a valid email address.
If you can only check on the back end, I'd do something like:
emailStr = "#gmail.com";
if(str.Contains(emailStr) && str.length == emailStr.length)
{
//your processing here
}
You can also use Regex matching, but I'm not nearly familiar enough with that to tell you what pattern you'd need.
If you're looking for just anything containing "#gmail.com", Jon's answer is your best bets.

Categories

Resources