4

I want to find an index of a string only for first three char from an array

I have an array of month

string[] arrayEnglishMonth = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };

If I write

     int t_ciMonth=8;(AUGUST)
     int pos = Array.IndexOf(t_caMonth, arrayEnglishMonth[t_ciMonth - 1]);

But if I want the Index for only first 3 character i.e AUG how to find it?

10
  • You mean you want to find the index of the first string in the array that starts with a given string, e.g. "AUG"? Commented Aug 5, 2013 at 6:28
  • 1
    You do know about DateTimeFormatInfo.GetMonthName and DateTimeFormatInfo.GetAbbreviatedMonthName? Commented Aug 5, 2013 at 6:32
  • yes.............................. Commented Aug 5, 2013 at 6:32
  • @Proneet, what is t_caMonth? Commented Aug 5, 2013 at 6:33
  • Is that some sort of C variable naming convention? Commented Aug 5, 2013 at 6:36

6 Answers 6

6
arrayEnglishMonth.ToList().FindIndex(s => s.Substring(0,3) == "AUG");
Sign up to request clarification or add additional context in comments.

3 Comments

looks elegant but I wonder what happens if the iteration reaches to the end of the list.. s.Substring(0,3) will not yield exception for out of range?
Why is this an answer if he's not looking into the arrayEnglishMonth, but in the t_caMonth array?
@G.Y. reaches the end as in it doesn't find a match? -1 is returned
4

You have two options I can think of:

  1. Linq only aproach that looks like this:

    var index = arrayEnglishMonth.Select((v, i) => new { v, i })
                                 .Where(c => c.v.StartsWith("AUG"))
                                 .Select(c => c.i)
                                 .First();
    

    This will first iterate over existing array, create enumerable of anonymous objects holding values and indexes, where predicate passed in Where returns true, after that select only index and take the first element from enumerable.

    Demo

  2. Find respective month using Linq and then use IndexOf method:

    var item = arrayEnglishMonth.First(c => c.StartsWith("AUG"));
    var index = Array.IndexOf(arrayEnglishMonth, item);
    

    Demo

4 Comments

Where do you use t_caMonth in your answer? Take a more attentive look to the code in the question.
@AlexFilipovici As far as I understood question OP was stuck with finding index in arrayEnlishMonth. Once s/he has index it's not a big deal to check if that index exists in another array.
Regarding 1, it's doing something else: There's only 1 iteration over the array, for each element, an anonymous object is created and if it starts with AUG, its second element is returned.
@ytoledano Yeah, you are right. WhereSelectEnumerableIterator will be used for iteration over array. I'll update answer.
2

You can do this with a little Linq:

string[] arrayEnglishMonth = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
string[] t_caMonth = { ... };
string search = arrayEnglishMonth[7].Substring(0, 3); // "AUG";
int pos = t_caMonth
    .Select((s, i) => new { s, i }).Dump()
    .Where(x => x.s == search)
    .Select(x => x.i)
    .DefaultIfEmpty(-1).First();

Or more simply:

int pos = t_caMonth.TakeWhile(s => s != search).Count();

Although this last solution will return t_caMonth.Length instead of -1 if no matching element is found.

3 Comments

@AlexFilipovici t_caMonth is an array which I get at run time
@p.s.w.g I want to get index from an array t_caMonth not the count
@Proneet Sorry I misunderstood what you were looking for. I've updated my answer. However, the Count in the second example doesn't do what you think it does. TakeWhile(...).Count() iterates through the list on til it finds an element that doesn't meet the condition (in this case, until it finds an a string that equals search) and then returns the number of items it had to go through until it found one--i.e. the index of the first match.
0

This is mine way to achieve this

string[] arrayEnglishMonth = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
var searcheditem = arrayEnglishMonth.FirstOrDefault(item => item.Substring(0, 3) == "AUG");
if(searcheditem != null)
var itemIndex = Array.IndexOf(arrayEnglishMonth, searcheditem);

but @wdavo answer is better

Comments

0

If the t_caMonth has upper casing and it's values have only 3 letters, you may use:

 int pos = Array.IndexOf(t_caMonth, arrayEnglishMonth[t_ciMonth - 1]
     .Substring(0,3));

In order to manage casing and values with more than 3 characters, you could have:

var pos = -1;
var sel = t_caMonth
    .Select((i, index) => new { index, i = i.ToUpper() })
    .Where(i => 
        i.i.Substring(0,3) == arrayEnglishMonth[t_ciMonth - 1].Substring(0, 3))
    .Select(i => i.index);
if (sel.Count() > 0)
    pos = sel.FirstOrDefault();

You may also create a List<string> from your t_caMonth array:

var pos2 = t_caMonth
    .ToList()
    .FindIndex(i => 
        i.ToUpper().Substring(0, 3) == 
            arrayEnglishMonth[t_ciMonth - 1].Substring(0, 3));

Comments

0

Try using the following, i think it is the fastest
Array.FindIndex(strArray, s => s.StartsWith("AUG"));

Cheers.

1 Comment

why do ppl are so obsessed with linq that they forget there are simple functions to do the job for you :)

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.