0

I have some strings and I would like to get the Index Number out from them.

Here is the example.

        var x = "FundList[10].Amount";
        var y = "FundList[11].Amount";
        var z = "FundList[15].Amount";

I simply want to get the 10,11,15 and put them into an array of Int.

Currently, I am using a stupid way, which is to replace "FundList[", "]" and ".Amout" with "".

I am wondering if there is a better way to do so.

Update

Here are some clarifications. Here is my code.

This is my part of my PartialView.

    @{
    var txtIndexName = "FundList[" + Model.Index + "].Index";
    var txtAmountName = "FundList[" + Model.Index + "].Amount";
    var dropFiscalYearName = "FundList[" + Model.Index + "].FiscalYear";
}

Amount: <input type="text" name="@txtAmountName" id="@txtAmountName" /> 

Here is the JavaScript to call the PartialView. Each time when user click on a anchor link, the PartialView will be called.

function LoadContractOptionFundingPlanBlockByIndexNumber(indexNumber) {

$.ajax({
    type: "POST",
    url: "/Json/LoadContractOptionFundingPlanPartialView",
    data: JSON.stringify({ index: indexNumber }),
    contentType: "application/json; charset=utf-8"
}).success(function (result) {

    $("#ContractOptionFundingPlanBlock").append(result);

});
}

function GenerateOptionFundingPlanBlock() {
$("#lnkAddFundingBlock").click(function () {

    LoadContractOptionFundingPlanBlockByIndexNumber(currentIndexNumber);
    currentIndexNumber++;
});
}

$(document).ready(function () {

GenerateOptionFundingPlanBlock();

});

var currentIndexNumber = 10;

Here is my View:

<form action="#" method="post" name="formCreateContracOption" id="formCreateContracOption">

@Html.AntiForgeryToken()

@Html.LabelForRequired(x=>x.ThisContractOption.OptionName)
@Html.ValidationMessageFor(x=>x.ThisContractOption.OptionName)
@Html.TextBoxFor(x=>x.ThisContractOption.OptionName) <br/><br/>

Period of Performance

@Html.TextBoxFor(x=>x.ThisContractOption.OptionStartDate)
@Html.TextBoxFor(x=>x.ThisContractOption.OptionEndDate) <br /><br />

<a id="lnkAddFundingBlock" href="#">Add Funding Plan</a>  <br/><br/>

<div id="ContractOptionFundingPlanBlock"></div>

<input type="submit" id="btnCreateContractOption" name="btnCreateContractOption" value="Submit" />

</form>

After all, when user clicks on the Submit button, the whole thing will be posted to the controller.

Here is my Controller.

        [HttpPost]
    public ActionResult CreateContractOption(int contractId, ContractOptionCreateEditViewModel viewModel, FormCollection form)
    {
        var fundList = new List<OptionFundingPlanObject>();

        var allOptionAmountKeyList = form.AllKeys.Where(x => x.Contains("FundList") && x.Contains("Index")).ToList();

        var indexNumberList = new List<int>();

        foreach(var thisKey in allOptionAmountKeyList)
        {
            var convertedIndex = Convert.ToInt32(Regex.Match(thisKey, @"\d+").Value);
            indexNumberList.Add(convertedIndex);
        }

        return View();
    }

The reason I am asking is because it is not simply a How to Post a List to the controller question.

When the List starts with a ZERO index, and every other index is in a sequence, it is pretty easy to handle.

In my case, user may generate a new Option, by calling my Partial View. User will have the ability to remove the generated option, and create a new one. The index then changed. In this case, I have to find another way to solve the problem.

halfer
  • 19,824
  • 17
  • 99
  • 186
HorseKing
  • 454
  • 6
  • 19
  • 2
    I don't think that way is so stupid, if it works, it's not stupid – Alex Jan 02 '15 at 16:08
  • Possible duplicate? – Murray Foxcroft Jan 02 '15 at 16:09
  • 1
    What might be stupid is why you are getting those strings. – crthompson Jan 02 '15 at 16:09
  • I must say even if this does work. I still think its stupid. Why not set x y and z to integers and use it that way? – JKennedy Jan 02 '15 at 16:09
  • 1
    Right. Why are you setting those strings in code? This seems like you're asking the wrong question. http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – aquinas Jan 02 '15 at 16:10
  • oh guys, I was trying to make the question as simple as possible. Those string are actually the Key name from FormCollection, it is a name-vale pair. I need to get the value for each key. – HorseKing Jan 02 '15 at 16:12
  • 1
    But where are these strings coming from in the first place? Surely you're not really hardcoding them and then turning around and parsing them? I understand that you were asking a very specific question, and that's fine, but I'm just wondering if we can you give a way to avoid this question altogether. For example, are you passing these strings back from your view to your controller? If so, why aren't you just passing the integers back? Why are you passing "FundList[indexNumber].Amount". That's kind of weird in my opinion. Or maybe you're doing something else? Or you can ignore this too. :) – aquinas Jan 02 '15 at 16:15

5 Answers5

5
var x = "FundList[10].Amount";
int xIndex = Convert.ToInt32(Regex.Match(x,@"\d+").Value); //10

This is a werid question though. What are you doing? :)

aquinas
  • 23,318
  • 5
  • 58
  • 81
  • hah, thanks for the reply. I am posting a list of object to the controller. The index of those objects may not be in sequence. It is easy to handle when the index starts with 0, and each one in sequence.It may require some extra steps to handle my situation. – HorseKing Jan 02 '15 at 16:10
  • So...wait. Is your code example in JavaScript or in C#? – aquinas Jan 02 '15 at 16:11
  • Can you please explain the Regex commands. Maybe others can learn from this. – John Alexiou Jan 02 '15 at 16:16
1

If you are always going to have the strings in the form you provided you can split it on the brackets and get the item from the returned string array:

var x = "FundList[10].Amount";
var num = x.Split('[', ']')[1];
int res = Convert.ToInt32(num);
PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
0

Maybe something like: Online Demo

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string text = "FundList[15].Amount";
         var result = Convert.ToInt32(Regex.Replace(text, @"[^\d]+",""));
        Console.WriteLine("Result is = {0}", result);
    }
}
Dalorzo
  • 19,834
  • 7
  • 55
  • 102
0

As its fixed as FundList simply:

int i = int.Parse(x.Substring(9, x.IndexOf(']') - 9));
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

If you prefer LINQ syntax to Regex:

var x = "FundList[10].Amount";
int n = Int32.Parse(new string(x.Where(c => Char.IsDigit(c)).ToArray()));  //10
w.b
  • 11,026
  • 5
  • 30
  • 49