将 CSV 字符串解析为整数数组

发布于 2024-08-11 21:58:42 字数 1817 浏览 8 评论 0原文

我有一个文本框字段输入 123,145,125 我将此字段分隔成整数数组。如果一切都解析正确,则验证该字段为 true 或 false。

代码:

private bool chkID(out int[] val) 
{
    char[] delimiters = new char[] { ',' };
    string[] strSplit = iconeID.Text.Split(delimiters);  


    int[] intArr = null;
    foreach (string s in strSplit) //splits the new parsed characters 
    {
        int tmp;
        tmp = 0;
        if (Int32.TryParse(s, out tmp))
        {
            if (intArr == null)
            {
                intArr = new int[1];
            }
            else
            {
                Array.Resize(ref intArr, intArr.Length + 1);
            }
            intArr[intArr.Length - 1] = tmp;
        }

        if (Int32.TryParse(iconeID.Text, out tmp))
        {
            iconeID.BorderColor = Color.Empty;
            iconeID.BorderWidth = Unit.Empty;

            tmp = int.Parse(iconeID.Text);
            val = new int[1];
            val[0] = tmp;
            return true;
        }


    }
    val = null;
    ID.BorderColor = Color.Red;
    ID.BorderWidth = 2;
    return false;
}

//新代码: private bool chkID(out int[] val) //checkID 函数的布尔状态 { string[] split = srtID.Text.Split(new char[1] {','}); 列表数字 = new List(); int 解析;

        bool isOk = true;
        foreach( string n in split){
            if(Int32.TryParse( n , out parsed))
                numbers.Add(parsed);
            else
                isOk = false;
        }
        if (isOk){
            strID.BorderColor=Color.Empty;
            strID.BorderWidth=Unit.Empty;
            return true;
        } else{
            strID.BorderColor=Color.Red;
            strID.BorderWidth=2;
            return false;
        }
            return numbers.ToArray();
        }

I have a text box field inputs 123,145,125 I to separate this field into an array of integers. And validate this field true or false if everything is parsed right.

CODE:

private bool chkID(out int[] val) 
{
    char[] delimiters = new char[] { ',' };
    string[] strSplit = iconeID.Text.Split(delimiters);  


    int[] intArr = null;
    foreach (string s in strSplit) //splits the new parsed characters 
    {
        int tmp;
        tmp = 0;
        if (Int32.TryParse(s, out tmp))
        {
            if (intArr == null)
            {
                intArr = new int[1];
            }
            else
            {
                Array.Resize(ref intArr, intArr.Length + 1);
            }
            intArr[intArr.Length - 1] = tmp;
        }

        if (Int32.TryParse(iconeID.Text, out tmp))
        {
            iconeID.BorderColor = Color.Empty;
            iconeID.BorderWidth = Unit.Empty;

            tmp = int.Parse(iconeID.Text);
            val = new int[1];
            val[0] = tmp;
            return true;
        }


    }
    val = null;
    ID.BorderColor = Color.Red;
    ID.BorderWidth = 2;
    return false;
}

//new Code:
private bool chkID(out int[] val) //bool satus for checkID function
{
string[] split = srtID.Text.Split(new char[1] {','});
List numbers = new List();
int parsed;

        bool isOk = true;
        foreach( string n in split){
            if(Int32.TryParse( n , out parsed))
                numbers.Add(parsed);
            else
                isOk = false;
        }
        if (isOk){
            strID.BorderColor=Color.Empty;
            strID.BorderWidth=Unit.Empty;
            return true;
        } else{
            strID.BorderColor=Color.Red;
            strID.BorderWidth=2;
            return false;
        }
            return numbers.ToArray();
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

秋日私语 2024-08-18 21:58:42

给定的函数似乎做得太多了。这是回答您的标题所暗示的问题的一个:

//int[] x = SplitStringIntoInts("1,2,3, 4, 5");

static int[] SplitStringIntoInts(string list)
{
    string[] split = list.Split(new char[1] { ',' });
    List<int> numbers = new List<int>();
    int parsed;

    foreach (string n in split)
    {
        if (int.TryParse(n, out parsed))
            numbers.Add(parsed);
    }

    return numbers.ToArray();
}

编辑(根据您对问题的评论)

您已经定义了该函数需要执行的三件事。现在您只需为每个创建方法即可。以下是我对如何实施它们的猜测。

int[] ValidateIDs(int[] allIDs)
{
    List<int> validIDs = new List<int>(allIDs);

    //remove invalid IDs

    return validIDs.ToArray();
}

void DownloadXmlData(int[] ids)
{
    ...
}

现在您只需执行新函数:

void CheckIconeID(string ids)
{
    int[] allIDs = SplitStringIntoInts(ids);
    int[] validIDs = ValidateIDs(allIDs);

    DownloadXmlData(validIDs);
}

The given function seems to do too much. Here's one that answers the question implied by your title:

//int[] x = SplitStringIntoInts("1,2,3, 4, 5");

static int[] SplitStringIntoInts(string list)
{
    string[] split = list.Split(new char[1] { ',' });
    List<int> numbers = new List<int>();
    int parsed;

    foreach (string n in split)
    {
        if (int.TryParse(n, out parsed))
            numbers.Add(parsed);
    }

    return numbers.ToArray();
}

EDIT (based on your comment on the question)

You've defined the three things this function needs to do. Now you just need to create methods for each. Below are my guesses for how you could implement them.

int[] ValidateIDs(int[] allIDs)
{
    List<int> validIDs = new List<int>(allIDs);

    //remove invalid IDs

    return validIDs.ToArray();
}

void DownloadXmlData(int[] ids)
{
    ...
}

Now you just execute your new functions:

void CheckIconeID(string ids)
{
    int[] allIDs = SplitStringIntoInts(ids);
    int[] validIDs = ValidateIDs(allIDs);

    DownloadXmlData(validIDs);
}
无力看清 2024-08-18 21:58:42

我真的很想对@Austin Salonen 的答案发表评论,但它不适合。对于所提出的问题来说,这是一个很好的答案,但我想更广泛地扩展 csv/int 转换部分的讨论。

提议的“安全”功能(如果您不想知道坏值,则具有重载)...

    public static int[] SplitAsIntSafe (this string csvString) {
        List<string> badVals;
        return SplitAsIntSafe(csvString, ',', out badVals);
    }
    public static int[] SplitAsIntSafe (this string delimitedString, char splitChar, out List<string> badVals) {
        int         parsed;
        string[]    split   = delimitedString.Split(new char[1] { ',' });
        List<int>   numbers = new List<int>();
        badVals             = new List<string>();

        for (var i = 0; i < split.Length; i++) {
            if (int.TryParse(split[i], out parsed)) {
                numbers.Add(parsed);
            } else {
                badVals.Add(split[i]);
            }
        }
        return numbers.ToArray();
    }

提议的“快速”功能...

    public static int[] SplitAsIntFast (this string delimitedString, char splitChar) {
        string[]    strArray = delimitedString.Split(splitChar);
        int[]       intArray = new int[strArray.Length];

        if(delimitedString == null) {
            return new int[0];
        }
        for (var i = 0; i < strArray.Length; i++) {
            intArray[i] = int.Parse(strArray[i]);
        }
        return intArray;
    }

无论如何,希望这对某人有帮助。

I really wanted to comment on @Austin Salonen's answer, but it didn't fit. It is a great answer for the question asked, but i wanted to expand the discussion a bit more generally on csv/int conversion part.

Proposed "safe" function (with overload in case you don't want to know the bad values)...

    public static int[] SplitAsIntSafe (this string csvString) {
        List<string> badVals;
        return SplitAsIntSafe(csvString, ',', out badVals);
    }
    public static int[] SplitAsIntSafe (this string delimitedString, char splitChar, out List<string> badVals) {
        int         parsed;
        string[]    split   = delimitedString.Split(new char[1] { ',' });
        List<int>   numbers = new List<int>();
        badVals             = new List<string>();

        for (var i = 0; i < split.Length; i++) {
            if (int.TryParse(split[i], out parsed)) {
                numbers.Add(parsed);
            } else {
                badVals.Add(split[i]);
            }
        }
        return numbers.ToArray();
    }

Proposed "fast" function ....

    public static int[] SplitAsIntFast (this string delimitedString, char splitChar) {
        string[]    strArray = delimitedString.Split(splitChar);
        int[]       intArray = new int[strArray.Length];

        if(delimitedString == null) {
            return new int[0];
        }
        for (var i = 0; i < strArray.Length; i++) {
            intArray[i] = int.Parse(strArray[i]);
        }
        return intArray;
    }

Anyway, hope this helps someone.

〃安静 2024-08-18 21:58:42

可能值得您花时间查看一下这个 FileHelper 以及 CSV 阅读器

希望它们能帮助您...
小心,
汤姆

It might be worth your while to check out this FileHelper and also CSV Reader

Hope they will help you...
Take care,
Tom

岁月染过的梦 2024-08-18 21:58:42

有一个很好的免费库用于解析 CSV 文件: FileHelpers

    using FileHelpers;

    // First declare the record class

    [Delimitedrecord(";")]
    public class SampleType
    {
        public string Field1;
        public int    Field2;
    }


    public void ReadExample()
    {
        FileHelperEngine engine = new FileHelperEngine(typeof(SampleType));

        SampleType[] records;    

        records = (SampleType[]) engine.ReadFile("source.txt");

        // Now "records" array contains all the records in the
        // sourcefile and can be acceded like this:

        int sum = records[0].Field2 + records[1].Field2;
    }

There is a good free library for parsing CSV files: FileHelpers

    using FileHelpers;

    // First declare the record class

    [Delimitedrecord(";")]
    public class SampleType
    {
        public string Field1;
        public int    Field2;
    }


    public void ReadExample()
    {
        FileHelperEngine engine = new FileHelperEngine(typeof(SampleType));

        SampleType[] records;    

        records = (SampleType[]) engine.ReadFile("source.txt");

        // Now "records" array contains all the records in the
        // sourcefile and can be acceded like this:

        int sum = records[0].Field2 + records[1].Field2;
    }
十雾 2024-08-18 21:58:42
public bool ParseAndCheck(string source,
    out IList<int> goodItems, out IList<string> badItems)
{
    goodItems = new List<int>();
    badItems = new List<string>();

    foreach (string item in source.Split(','))
    {
        int temp;
        if (int.TryParse(item, out temp))
            goodItems.Add(temp);
        else
            badItems.Add(item);
    }

    return (badItems.Count < 1);
}
public bool ParseAndCheck(string source,
    out IList<int> goodItems, out IList<string> badItems)
{
    goodItems = new List<int>();
    badItems = new List<string>();

    foreach (string item in source.Split(','))
    {
        int temp;
        if (int.TryParse(item, out temp))
            goodItems.Add(temp);
        else
            badItems.Add(item);
    }

    return (badItems.Count < 1);
}
雨后咖啡店 2024-08-18 21:58:42

在 .NET 2.0 中你可以这样写

string test = "123,14.5,125,151,1.55,477,777,888";

bool isParsingOk = true;


int[] results = Array.ConvertAll<string,int>(test.Split(','), 
    new Converter<string,int>(
        delegate(string num)
        {
            int r;
            isParsingOk &= int.TryParse(num, out r);
            return r;
        }));

In .NET 2.0 you could write

string test = "123,14.5,125,151,1.55,477,777,888";

bool isParsingOk = true;


int[] results = Array.ConvertAll<string,int>(test.Split(','), 
    new Converter<string,int>(
        delegate(string num)
        {
            int r;
            isParsingOk &= int.TryParse(num, out r);
            return r;
        }));
殤城〤 2024-08-18 21:58:42

这很简单,而且我认为效果很好。它只返回有效数字:

static int[] SplitStringIntoInts(string list)
{            
    int dummy;            
    return (from x in list.Split(',')
            where int.TryParse(x.ToString(), out dummy)
            select int.Parse(x.ToString())).ToArray();           
}

This is simple and I think works pretty well. It only return valid numbers:

static int[] SplitStringIntoInts(string list)
{            
    int dummy;            
    return (from x in list.Split(',')
            where int.TryParse(x.ToString(), out dummy)
            select int.Parse(x.ToString())).ToArray();           
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文