【问题标题】:Access Elements which are in a string-array within a List<>访问 List<> 中字符串数组中的元素
【发布时间】:2015-02-27 07:23:16
【问题描述】:

我有几个字符串数组,都采用这种方案:

string[0] = article number; string[1] = description; string[2] = amount;

现在,列表包含大约 50 个这样的数组。 现在我想知道,如何访问数组中的这些值。

例如: 我在文本框中输入文章编号。 现在应该搜索数组以在其“0”索引中包含文章编号。 我该如何做到这一点? 我试过类似的东西:

for(int i = 0; i<List.length;i++)
{
   if(List[i[0]] == txtBox.Text;
   {
       doSomething();
       break;
   }
}

当然,这还不是很好。

【问题讨论】:

  • 当然不行,这都是面向对象编程的。你需要一门课
  • 你可以建立一个新的类,比如说Order,属性为articleNumber、description和amount,然后你创建一个这些对象的数组并使用已经提到的解决方案进行搜索。

标签: c# arrays collections


【解决方案1】:

现有代码存在一些问题:

  1. 要访问另一个索引中的索引,[] 需要在内部而不是内部相互跟踪。即 [0][0] 不是 [0[0]]
  2. 因为 if 语句没有任何 {},所以循环将在第一次迭代后中断。

试着改成这样

for(int i = 0; i<List.length;i++)
{
   if(List[i][0] == txtBox.Text)
   {    
      doSomething();
      break;
   }
}

正如其他 cmets 指出的那样,最好使用类和 linq 来处理类似这样的事情

public class MyClass 
{
   public string ArticleNumber {get; set;}
   public string Description {get; set;}
}

使用 linq 搜索它

var list = new List<MyClass>()
if (list.Any(i => i.ArticleNumber.Equals(txtBox.Text)))
{
    DoSomething();
}

【讨论】:

  • 你是对的 if{} 事情,这只是一个例子,而不是我的整个代码。我匆忙忘记了
【解决方案2】:

我建议你定义一个这样的类

public class Article
{
    public string ArticleNumber { get; set;}
    public string Description { get; set; }
    public string Amount { get; set; } 
}

其目的是保存有关文章的所有信息,这些信息现在存储在一个数组中,这不是最好的方法。

那么你应该创建一个arcticles列表:

var articles = new List<Article>();

您将在其中添加您的文章。

这样做,您想要的是以下内容:

// This would check if there is any article in your list, whose article         
// number starts with the letters in the txtBox.Text
if(articles.Any(article=>article.ArticleNumber.Contains(txtBox.Text))
    DoSomething();

// If you want to search if there is any article, whose article number
// matches the inserted number in the textbox, then you have to change the 
// above
if(articles.Any(article=>article.ArticleNumber == txtBox.Text))
    DoSomething();

如果您的意图是使用可能存在的文章,那么我们应该将上面的内容更改为以下内容:

var article = articles.FirstOrDefault(article=>
                  article.ArticleNumber.Contains(txtBox.Text));

var article = articles.FirstOrDefault(article=>
                  article.ArticleNumber == txtBox.Text);

if(article!=null)
    DoSomething();

这个版本和第一个版本的区别在于你知道你可以使用article如果找到它,而无需再次查询你的序列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多