我在上课时填充了以下列表:
List<string> stringCollection = new List<string>();
我有很多在上课前声明的静态字符串。 这些字符串是根据条件表达式的集合添加到我的列表中的,这意味着它会改变我放入列表中的字符串类型,例如:
static string DescriptionText1 = "blabla",
DescriptionText2 = "blabla",
MagnitudeText1 = "blabla",
MagnitudeText2 = "blabla";
if(number < 2)
{
stringcollection.Add(DescriptionText1)
}
else
{
stringcollection.Add(DescriptionText2)
}
//Magnitude
if(magnitude > 128 && number < 256)
{
stringcollection.Add(MagnitudeText1)
}
else
{
stringcollection.Add(MagnitudeText2)
}
...
然后我将列表传递给我的方法,我想在其中检索字符串,如下所示:
public void Collection(List<string> ts)
{
string Description = ts.Find(DescriptionText); <--- my guess
string Magnitude = ts.Find(MagnitudeText);
}
如何在我的列表中找到正确的字符串,并将其写入我的方法中新声明的字符串? - 即使它们被附加因此 1,2,3 ... 6,7
最佳答案
因为你总是先输入 Description
然后输入 Magnitude
,你可以这样做:
ts[0] // description
ts[1] // magnitude
或者,考虑编写一个具有以下两个属性的类:
// I don't know what these two things represent, please name it properly in your code!
class DescriptionMagnitude {
public string Description { get; }
public string Magnitude { get; }
public DescriptionMagnitude(string description, string magnitude) {
Description = description;
Magnitude = magnitude;
}
}
然后创建这个类的一个实例并传递它。
编辑:
来自您的评论:
and then i would be able to search for my int variable?
您似乎想要找到与字符串关联的整数。但是,DescriptionText1
中的1
只是标识符的一部分。为什么不只存储整数而不是字符串?
根据您对字符串所做的操作,枚举可能是合适的:
enum Descriptions {
Foo = 0,
Bar = 1
Fizz = 2
}
关于c# - 按字符串名称在字符串列表中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310267/