C# 从IEnumerable中的字符串获取值
我有以下代码C# 从IEnumerable中的字符串获取值,c#,string,ienumerable,C#,String,Ienumerable,我有以下代码 public const string boy = "B"; public const string girl = "G"; private gender(string description, string value) { Description = description; Value = value; } public static IEnumerable<gender> Ge
public const string boy = "B";
public const string girl = "G";
private gender(string description, string value)
{
Description = description;
Value = value;
}
public static IEnumerable<gender> GetAll()
{
yield return new gender("Boy", boy);
yield return new gender("Girl", girl);
}
public const string boy=“B”;
public const string girl=“G”;
私有性别(字符串描述、字符串值)
{
描述=描述;
价值=价值;
}
公共静态IEnumerable GetAll()
{
产量回报新性别(“男孩”,男孩);
收益回报新性别(“女孩”,女孩);
}
我想找到一种方法,给我的程序一个字符串“Boy”,并得到它应该得到的字符串“B”。这是怎么可能的?与上一个答案几乎相同,但收到了错误值的检查:)
var param = "Boy";
var someBoy = GetAll().Where(g => g.Description == param).Select(g => g.Value).Single();
为什么要使用IEnumerable方法和性别类?在这种情况下,应该使用枚举。按如下方式定义枚举:
public Enum Gender { Boy, Girl };
然后,您可以执行以下操作:
Gender gender = Gender.Boy;
string description = gender.ToString();
// If you want to use 'B' as value...
string value = description[0];
在此处阅读有关枚举的更多信息:如果不能保证搜索命中率,请使用SingleOrDefault()而不是Single()。如果找不到匹配项,SingleOrDefault将返回null,而Single将抛出异常
Gender gender = Gender.Boy;
string description = gender.ToString();
// If you want to use 'B' as value...
string value = description[0];