2017-01-05 104 views
0

我自学自我C#并一直在试图弄清楚如何让用户能够从列表中删除一个项目及其索引号通过输入自己的索引号或键入单词。允许用户从列表中删除项目

我已经一派,尝试了许多方法来做到这一点,但每次我想出了一个办法时,它会删除元素我会选择,但指数并没有消失。示例(列表:0.hat,1.mat,2.fat,每当我输入“1”或“mat”来移除'mat'时,它会显示列表为0.hat 1.fat,我希望它显示0.hat,2.fat)

这是我最近尝试这样做:

string[] stringList = new string[] { "hat", "mat", "fat" }; 
     //Creating list 
     List<string> list = new List<string>(stringList); 
     string answer; 
     //ordering list backwards Z-A 
     list.Sort((a, b) => -1 * a.CompareTo(b)); 
     //loop to allow them to continue removing items 
     while (true) 
     { 
      //Displaying list to console 
      for (int i = 0; i < list.Count; i++) 
      { 
       //display list 
       Console.WriteLine("{0}.{1}", i, list[i]); 
      } 

      //This is blank 
      Console.WriteLine(); 
      //instructions what to do 
      Console.WriteLine("Choose from the list to remove an item: "); 
      //this will store the users input 
      answer = Console.ReadLine(); 
      answer = answer.ToLower(); 

      -- this is where I put the removing at -- 

      //Making sure user does not crash program 
      if (!string.IsNullOrEmpty(answer)) 
      { 
       var index = list.FindIndex(i => i == answer); 
       foreach (var item in list) 
       { 
        if (index >= 0) 
        { 
         list.RemoveAt(index); 
        } 
       } 
      } 

我这里使用的不会删除任何东西的方法。 我很难理解。 如果有人能提供一些很好的见解。谢谢

+0

btw,在C#中的评论不包含在双折线像你在这里。他们从//开始或者被封闭为:/ *这里有一些注释*/ –

+0

是的,我知道那部分不在我原来的代码中。 – Pandda

回答

1

您可以删除字符串,而不必通过将字符串传入.Remove()方法来查找索引。也删除foreach循环,因为它是多余的,你没有做任何事情。

if (!string.IsNullOrEmpty(answer)) 
{ 
    list.Remove(answer); 
} 

使用Dictionary您可以访问密钥或值,并根据需要删除。

var list = new Dictionary<int, string> 
{ 
    { 0, "hat" }, 
    { 1, "mat" }, 
    { 2, "fat" } 
}; 

var item = list.FirstOrDefault(kvp => kvp.Value == "hat"); 
// Remove by value 
list.Remove(item.Key); 
// Remove by key 
list.Remove(0); 

打印结果

foreach (var kvp in list) 
{ 
    Console.WriteLine(kvp.Key + " " + kvp.Value); 
} 
+0

它只在我输入单词时才起作用,但它不会像我之前在示例中所述的那样删除索引。我希望能够通过输入索引号或输入旁边的索引号来删除它。 – Pandda

+0

你想输入'0.hat'去除该值? – abdul

+0

不,或者允许他们输入'0'来移除帽子或输入'帽子'来移除它,但不管他们输入了什么,我也希望索引消失。 我想出了如何去除元素,但是每当我输入'0'时,'帽子'就会消失,但是'垫子的索引变为0时,它应该是1 ...如果这样做有任何意义 – Pandda

1

而不是使用列表,使用字典,其中的关键是项目的索引。在这种情况下,当您删除一个项目时,您将保留项目的原始索引。

0

消除由指数

list.Remove(answer); 

消除由数据

var index = list.FindIndex(i => i == answer); 

    list.RemoveAt(index); 
+0

我应该为它创建一个函数吗? – Pandda

+0

如果你想从不同的位置为这项工作调用这个函数,是的,你应该。 – Jze

0

原题:

如何“与它的索引号一起从列表中无论是 删除项目输入他们的索引号码或输入单词。“

在C#中有很多方法可以做到这一点。甚至有多种类型。你发现了一个,List<T>,这当然是一种方法,但可能不是最好的。你也可以做一串字符串。 Systems.Collections.Generic命名空间中还有其他几种类型的集合,以及List<T>

但最简单的方法就是使用Dict<TKey, TValue>

怎么样?看看我提供的链接中的例子,或者做这样的事情:

var a = new Dictionary<int, string>(){ 
    {0, "hat"}, 
    {1, "mat"}, 
    {2, "fat"} 
}; 

a.Remove(0); // remove by key 
a.Where(i => i.Value != "mat"); // remove by value 
+0

“通过键删除”意味着通过输入索引号,“按值删除”意味着通过在此示例末尾键入单词,您将只剩下一个包含一个元素的词典:“fat”。 –