从列表中获取数据

时间:2014-05-14 18:31:58

标签: c# visual-studio list windows-forms-designer

我需要从列表中获取数据,但有序的mer意味着订单,但我的代码没有用完。

if (item is TextBoxUniversal)
{
    foreach (string i in itemlist)
    {
        ItemValorEntity x = new ItemValorEntity();
        x.Item_Id = i[itemIndex].ToString();
        strItem = x.Item_Id;
        itemIndex += 1;
    }

    txt.Name = item.Name;
    txt = GetTexBox(txt.Name, groupBox1);
    itemValor.Item_Id = strItem;
    itemValor.cClave = Convert.ToString(cboGTTipoItems.SelectedValue);
    itemValor.Valor = txt.Text;
}

在列表中我有几个项目可以是101,102,103等。我需要按顺序获取它们。 该代码只能获得1但不是1是101

Solucionado

if (item is TextBoxUniversal)
                {
                    string _item = itemlist[itemIndex].ToString();
                    itemIndex++;

                    txt.Name = item.Name;
                    txt = GetTexBox(txt.Name, groupBox1);
                    itemValor.Item_Id = _item;
                    itemValor.cClave = Convert.ToString(cboGTTipoItems.SelectedValue);
                    itemValor.Valor = txt.Text;
                }

1 个答案:

答案 0 :(得分:2)

更新:

我删除了之前的答案,因为我相信这更像是您正在寻找的。能够对您收到的列表进行排序。你的问题仍然很难被问到,所以我要假设你暗示的一些假设。那些是:

  • 使用硬编码列表。
  • 对列表进行排序。
  • 向用户显示。

您希望查看排序的类是List(T).Sort,它提供了一种干净,快速,简单的方法来实现目标。可以找到详细信息here

我将使用更实际的场景,我们有一系列学生需要在输出给我们的用户之前对他们的分数/成绩进行排序。

开始构建我们的Student对象。

public class Student
{
     public string Name { get; set; }
     public int Score { get; set; }
     public string Grade { get; set; }
}

到目前为止,我们的对象非常简单,它包含:

  • 姓名(姓名)
  • 实际得分(数字表示)
  • 成绩(信函代表)

现在我们将IComparable<Student>实现到Student对象。这将隐式实现以下方法:

public int CompareTo(Student other)
{
    throw new NotImplementedException();
}

因此,我们将从方法中移除Exception并实施:

if(other == null)
     return 1;

else
     return this.Score.CompareTo(other.Score);

此少量代码将执行以下操作:

  • 如果对象为null,则会更大。
  • 它会将我们当前的属性与参数值进行比较。

现在我们需要做的就是实施:

// Create Our List
List<Student> student = new List<Student>();

// Add our Students to the List
student.Add(new Student() { Name = "Greg", Score = 100, Grade = "A+" });
student.Add(new Student() { Name = "Kelli", Score = 32, Grade = "F" });
student.Add(new Student() { Name = "Jon", Score = 95, Grade = "A" });
student.Add(new Student() { Name = "Tina", Score = 93, Grade = "A-" });
student.Add(new Student() { Name = "Erik", Score = 82, Grade = "B" });
student.Add(new Student() { Name = "Ashley", Score = 75, Grade = "C" });

// Apply our Sort.
student.Sort();

// Loop through Our List:
foreach (Student placement in student)
     listBox1.Items.Add(placement.Name + " " + placement.Score + " " + placement.Grade);

这将使它们按Ascending顺序排列。如果需要,您可以进行调整和配置以使其Descending,甚至更复杂。希望这是一个很好的起点。

此外,有些项目可以访问OrderByOrderByDescending。所以你实际上可以像Dictionary那样执行这样的代码。

student.OrderByDescending(s => s.Value);

你有很多可能性,希望这能让你开始并能够稍微考虑一下你的实现。