1

I have an array which contains an elements as below

dec.02
Novemeber-2
Oct-6
.
.
.

Now suppose I want to find the index of dec.02 Suppose if an array in place of dec.02 there can be december-02. So I want to use linq with regex which finds the index. Date can be in any format

Regex will be (dec|december)\W*02

Can any one tell how to use regex with linq to find index from an array

2 Answers 2

1

Are you looking for something like that?

String[] data = new String[] {
  "dec.02",
  "Novemeber-2",
  "Oct-6",
  ...
};

// All the indexes
int[] indice = data
  .Select((line, index) => new {
     line = line,
     index = index})
  .Where(item => Regex.IsMatch(item.line, "Your regular expression"))
  .Select(item => item.index)
  .ToArray();

In case you want 1st such index only (-1 if no index found):

// First index (or -1 if there's no such index)
int result = data
  .Select((line, index) => new {
     line = line,
     index = index})
  .Where(item => Regex.IsMatch(item.line, "Your regular expression"))
  .Select(item => item.index + 1)
  .FirstOrDefault() - 1;
Sign up to request clarification or add additional context in comments.

2 Comments

No I want specific index of an element. above returns an array.
@user3138879: in that case use FirstOrDefault() instead of ToArray(), see my edit.
0

If I understand your question correctly, this can be a solution:

Regex regex = new Regex(@"(dec|december)\W*02");
string[] dates = { "dec.02", "Novemeber-2", "Oct-6" };
int i = dates.Length - dates.SkipWhile(s => !regex.IsMatch(s)).Count(); // based-0 index

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.