Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#-寻找一种在两种不同表示形式(数字和英文)之间解析字符串值的简单方法_C#_String_Parsing_Switch Statement - Fatal编程技术网

C#-寻找一种在两种不同表示形式(数字和英文)之间解析字符串值的简单方法

C#-寻找一种在两种不同表示形式(数字和英文)之间解析字符串值的简单方法,c#,string,parsing,switch-statement,C#,String,Parsing,Switch Statement,我目前正在为一些东西开发一个小助手应用程序,我想知道是否有更好的方法来完成这一点- 我有一个CSV文件,我正在读取到我的程序中,我正在将每行中的一个值从一个数值(始终是一个整数,介于1和5之间)解析为一个字符串值,以便在程序中更容易表示。保存文件时,我需要将字符串表示转换回数字表示。目前,我通过switch语句来实现这一点,但我知道必须有一种更简洁的方法来实现这一点 我当前使用的函数有两个参数。其中一个参数是一个字符串,它可以是我试图解析的值的数字表示或字符串表示,另一个值是一个布尔值,它告诉函

我目前正在为一些东西开发一个小助手应用程序,我想知道是否有更好的方法来完成这一点-

我有一个CSV文件,我正在读取到我的程序中,我正在将每行中的一个值从一个数值(始终是一个整数,介于1和5之间)解析为一个字符串值,以便在程序中更容易表示。保存文件时,我需要将字符串表示转换回数字表示。目前,我通过switch语句来实现这一点,但我知道必须有一种更简洁的方法来实现这一点

我当前使用的函数有两个参数。其中一个参数是一个字符串,它可以是我试图解析的值的数字表示或字符串表示,另一个值是一个布尔值,它告诉函数它应该以何种方式转换第一个参数。如果布尔参数为true,它将转换为数字表示,如果为false,它将转换为字符串表示。下面是我解析值的函数:

string ParseRarity(string rarity, bool toNumericalStr)
{
    if (toNumericalStr)
    {
        switch (rarity)
        {
            case "Very Common":
                return "1";
            case "Common":
                return "2";
            case "Standard":
                return "3";
            case "Rare":
                return "4";
            case "Very Rare":
                return "5";
        }
    }
    else
    {
        switch (rarity)
        {
            case "1":
                return "Very Common";
            case "2":
                return "Common";
            case "3":
                return "Standard";
            case "4":
                return "Rare";
            case "5":
                return "Very Rare";
        }
    }

    return "";
}

任何缩短此代码的帮助都将不胜感激,因此请提前“谢谢您”

我会创建一个类来存储这两个值,然后根据需要调用每个值

public class Rarity
{
    public Rarity(int numValue)
    {
        NumValue = numValue;

        switch(numValue)
        {
            case 1:
                StringValue = "Very Common";
                break;
            case 2:
                StringValue = "Common";
                break;
            case 3:
                StringValue = "Standard";
                break;
            case 4:
                StringValue = "Rare";
                break;
            case 5:
                StringValue = "Very Rare";
                break;
            default:
                StringValue = "";
                break;
        }
    }
    public int NumValue { get; }
    public string StringValue { get; }
}
当您加载CSV值时,您可以使用您提到的int值初始化类对象(在我的示例中是罕见的)

Rarity rarity = new Rarity(my_csv_int_value);
现在,您可以随时获取所需的价值

rarity.NumValue //1,2,3,4,5
rarity.StringValue //Very Common, Common, etc...

可能代码量差不多,但功能更为广泛,您不必一直解析字符串。

您可以做一些非常简单的事情,但应该将其分为两种方法。有一种方法可以做两件事,这真是糟糕的架构

public static class RarityConverter
{
    private static List<Tuple<int, string>> Rarities = new List<Tuple<int, string>>()
    {
        new Tuple<int, string>(1, "Very Common"),
        new Tuple<int, string>(2, "Common"),
        new Tuple<int, string>(3, "Standard"),
        new Tuple<int, string>(4, "Rare"),
        new Tuple<int, string>(5, "Very Rare"),
    };

    public static string ToString(int rarity)
    {
        return Rarities.FirstOrDefault(t => t.Item1 == rarity)?.Item2;
    }

    public static int? ToInt(string rarity)
    {
        return Rarities.FirstOrDefault(t => string.Compare(t.Item2, rarity, true) == 0)?.Item1;
    }
}
公共静态类稀有转换程序
{
私有静态列表稀有性=新列表()
{
新元组(1,“非常常见”),
新元组(2,“公共”),
新元组(3,“标准”),
新元组(4,“罕见”),
新元组(5,“非常罕见”),
};
公共静态字符串ToString(整数稀有)
{
返回稀有值.FirstOrDefault(t=>t.Item1==rarrity)?.Item2;
}
公共静态整数(字符串罕见)
{
返回稀有性.FirstOrDefault(t=>string.Compare(t.Item2,稀有性,true)==0)?.Item1;
}
}

您也可以使用Enum,但这需要您使用
DescriptionAttribute
将传入的字符串名称修饰/转换为Enum名称。

我也会给出一个答案,您可以创建一个包含稀有值的静态“repository”类。下划线存储机制是一个
字典
。这将迫使您的所有珍品都有一个唯一的密钥(int
int
),并且通过该密钥可以快速访问

public static class RarityRepository
{
    private static Dictionary<int, string> _values = new Dictionary<int, string>()
    {  
        { 1, "Very Common" },
        { 2, "Common" },
        { 3, "Standard" },
        { 4, "Rare" },
        { 5, "Very Rare" },
    };

    public static string GetStringValue(int input)
    { 
        string output = string.Empty;  // returns empty string if no matches are found
        _values.TryGetValue(input, out output);
        return output;
    }

    public static int GetIntValue(string input)
    {
        var result = _values.FirstOrDefault(x => string.Compare(x.Value, input, true) == 0);
        if (result.Equals(default(KeyValuePair<int,string>)))
        {
            return -1; // returns -1 if no matches are found
        }
        return result.Key;
    }
}
公共静态类稀有存储库
{
私有静态字典_值=新字典()
{  
{1,“非常常见”},
{2,“公共”},
{3,“标准”},
{4,“稀有”},
{5,“非常罕见”},
};
公共静态字符串GetStringValue(int输入)
{ 
string output=string.Empty;//如果找不到匹配项,则返回空字符串
_TryGetValue(输入、输出);
返回输出;
}
公共静态int GetIntValue(字符串输入)
{
var result=\u values.FirstOrDefault(x=>string.Compare(x.Value,input,true)==0);
if(result.Equals(默认值(KeyValuePair)))
{
return-1;//如果找不到匹配项,则返回-1
}
返回result.Key;
}
}

我做了一把小提琴,谢谢@Ron发现我的午夜大脑代码缺陷

如果您想要更简单,只需编写一个静态帮助器类,如下所示:

public class CodeConverter
{
    private static readonly string[] lookup = new []
    {
        "[Unknown]",
        "Very Common",
        "Common",
        "Standard",
        "Rare",
        "Very Rare"
    };

    public static string CodeToString(int code)
    {
        if (code < 0 || code > lookup.GetUpperBound(0)) code = 0;
        return lookup[code];
    }

    public static int StringToCode(string text)
    {
        int i = Array.IndexOf(lookup, text);
        return Math.Min(0,i);
    }
}
公共类编码转换器
{
私有静态只读字符串[]查找=新建[]
{
“[未知]”,
“非常普遍”,
“普通”,
“标准”,
“稀有”,
“非常罕见”
};
公共静态字符串CodeToString(int代码)
{
if(code<0 | | code>lookup.GetUpperBound(0))code=0;
返回查找[代码];
}
公共静态int-StringToCode(字符串文本)
{
inti=Array.IndexOf(查找,文本);
返回Math.Min(0,i);
}
}

我推荐

enum,即使有额外的装饰需求。对我来说,唯一的另一个竞争力量是数据应该存在于数据领域,而不是代码领域,因此我很可能不会在代码中明确地包含这些值

我不推荐这种确切的方法或OP的方法,我只是回答了简洁的需要

您的逻辑已经在字符串到字符串的转换中。为什么不双向O(1)查找?你可以有一个双向查找/字典

var lookup = new Dictionary<string, string>()
{  
    { ”1”, "Very Common" },
    { “2”,  "Common" },
    { “3”, "Standard" },
    { “4,” "Rare" },
    { “5”, "Very Rare" },
    { “Very Common”, “1” }
    //etc iPhone editing sucks
};
var lookup=newdictionary()
{  
{“1”,“非常常见”},
{“2”,“公共”},
{“3”,“标准”},
{“4”,“稀有”},
{“5”,“非常罕见”},
{“非常普通”,“1”}
//iPhone编辑真糟糕
};
您甚至可以只写出字典的正向查找部分,并在反向查找部分使用扩展方法或专用类ToTwoWayLookup填充,这样就不必键入2倍的值。(有关方法,请参阅已接受的答案),您还可以删除ContainsKey检查

然后在你的函数中去掉bool参数,只需在这个字典中查找。我不知道函数名是什么。。。FlipRepresentation

我可能会这样做

也许单独使用reverseLookup字典更有意义,因此您可以有两个名称更有意义的方法。简洁不是全部!努力使代码为其他人所理解!我更喜欢读数字(“普通”)、数字源于稀有名称、托拉里名称(“1”)或托拉里名称源于数字而不是Fl
public static class Rarities
{
    private static List<string> _rarityValues = new List<string>()
    {
        "Empty",
        "Very Common",
        "Common",
        "Standard",
        "Rare",
        "Very Rare"
    };

    public static string ToRarityString(this int rarity)
    {
        return _rarityValues[rarity];
    }

    public static int ToRairityInt(this string rarity)
    {
        return _rarityValues.IndexOf(rarity);
    }
}
   var rarityInt = 1;
   var rarityString = "Rare";

   var stringValue = rarityInt.ToRarityString();
   var intValue = rarityString.ToRairityInt();