简体   繁体   中英

How to read a string up until a comma, and then save that bit and display it?

Currently I am able to read all the lines of a text file, separating each list item whenever a comma { ", " } is reached. This is then displayed into a bootstrap collapse, however each item is displayed in their own collapse. So for example; say I were to have the following in my .txt file;

John, 0

Both John and 0 would have their own collapsible. Instead, I want John to be the only one with a collapsible, and I want the 0 which is an ID, to be invisible to the user. I would assume one would perhaps use the 'substring' property to do this, but how?

Below is my following code that performs as the example above;

@{
    var result = "";
    Array userData = null;
    char[] delimiterChar = { ',' };

    var dataFile = Server.MapPath("~/App_Data/Category.txt");
    userData = File.ReadAllLines(dataFile);

}

<div class="categoryList">

    @result
    @if (result == "")
    {
        foreach (String dataLine in userData)
        {
            foreach (string dataItem in dataLine.Split(delimiterChar))
            {

                <p>
                    <a data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
                        @dataItem
                    </a>
                </p>

            }

        }

    }

Any help on this matter would be greatly appreciated!

The Split method returns a string array, so you just need to index it to pick the first element, in this way your inner foreach would be redundant as well, so something like this is most probably what you're looking for:

foreach (String dataLine in userData)
{
    <p>
        <a....>
            @dataLine.Split(delimiterChar)[0]
        </a>
    </p>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM