0

I have an array arr[] of string type with array-items as follows:

arr[0]= "2/13/2019|202"
arr[1]= "2/14/2019|197"
arr[2]= "2/15/2019|101"
arr[4]= "2/16/2019|271"
arr[5]= "2/17/2019|199"

I want to get an array-item that matches my string "2/15/2019" so I can get "2/15/2019|101". in short, I just want to compare my string with the array-item string till "|" and rest strong will not be considered for comparison. how can I get it?

2
  • use contains() method Commented Feb 13, 2020 at 4:39
  • 3
    var results = arr.Where(x => x.StartsWith("2/15/2019")); Commented Feb 13, 2020 at 4:42

3 Answers 3

3

You could use Where and StartWith

var results = arr.Where(x => x.StartsWith("2/15/2019")); 

Additional Resources

Enumerable.Where Method

Filters a sequence of values based on a predicate.

String.StartsWith Method

Determines whether the beginning of this string instance matches a specified string.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use Linq to get the data you are looking for.

  • use Contains(string) to check if there is one or more elements that match your criteria
  • if it does, get the first one from the list (or you can assign that list to a variable and iterate through each of it)
  • Split the value and get the value after |
  • Use ?. after FirstOrDefault() method to ensure you dont get NullReferenceException when you run Split().
  • Use validation to ensure result is not null.
var result = arr.FirstOrDefault(x => x.Contains("2/15/2019"))?.Split('|')[1];
// result contains 101

Enumerable.FirstOrDefault: Returns the first element of a sequence, or a default value if no element is found

2 Comments

just need to remove?
@devSS If you use ?. before Split, you wont get Null Reference exceptions if there is no element in the array that contains that string. Try a search with string that doesnt match. ?. ensures there is always a value to run split on without exceptions.
1

Use where and contains

           string getdata = "2/15/2019";
            string[] arr = new string[5];
            arr[0] = "2/13/2019|202";
            arr[1] = "2/14/2019|197";
            arr[2] = "2/15/2019|101";
            arr[3] = "2/16/2019|271";
            arr[4] = "2/17/2019|199";

            var op = arr.Where(a => a.Contains(getdata)).FirstOrDefault();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.