2017-07-29 128 views
-1

所以我正在做这个任务,我相信你已经看到了它。 它基本上是一个列表,其中有一堆数组,这就是我所做的。如何正确地遍历数组以获取索引和值,以便我可以编辑它?

我宣布这个在我的课

static List<string[]> logBook = new List<string[]>(); 
    static string[] post = new string[2]; 

的顶部,然后我创建了一个函数/方法,它接受用户unput并将它作为一个条目。

private static void addToArray() 
    { 
     Console.WriteLine("Title: "); 
     DateTime dt = DateTime.Now; 
     string userInput = dt + " " + Console.ReadLine(); 
     Console.WriteLine("Message: "); 
     string userInputt = "\n\t\t" + Console.ReadLine(); 

     post = new string[2]; 
     post[0] = userInput; 
     post[1] = userInputt; 
     logBook.Add(post); 
    } 

现在我需要做的是创建一个搜索条目的功能,那么我应该能够编辑/删除它,如果我想,这是我在想什么做的,somethign沿这些线。

private static void searchArray() 
     { 
      post.Where(x => x.Contains("someString")); 
      for(int i = 0; i < logBook.Length; i++) 
       { 
       //And then use something here to get the index value of what I found with the .Contains method. 
       } 
     } 

现在,我遇到了搜索功能的问题,我不知道如何构建它?我的思维方式在这里甚至正确吗? 我该如何正确搜索一个项目并获取它的索引值?

+0

但是'post.Where(x => x.Contains(“someString”));'不会做任何事情...... –

+0

@WillemVanOnsem我会将“someString”更改为userInput,并且该值将保留到Console.ReadLine();所以.. string userInput = Console.ReadLine();还是我在这里想错了? –

回答

0

我认为首先你应该改变你使用的数据结构,所以你最终会得到这样的:

static Dictionary<string, Tuple<string, string>> logBook = new Dictionary<string, Tuple<string, string>>(); 

private static void addToArray() 
{ 
    var post = new Tuple<string, string>(userInput, userInputt); 
    logBook.Add(userInput, post); 
    logBook.Add(userInputt, post); 
} 

然后你就可以在O(1)时间easilly搜索:

private static void search() 
{ 
    var key = "your key here"; 
    if(logBook.ContainsKey(key)) 
    { 
     var post = logBook[key] 
     // edit here 
     post.Item1 = .... 
     post.Item2 = .... 
    } 
} 

该解决方案不处理重复输入,如果需要可以正确修改。

+0

事情是,我必须利用列表,我还需要一个二分查找+冒泡排序。 –

+0

对不起,你真正想要什么并不明显。你为什么需要使用List?当字典/哈希表更有效时,为什么需要使用二分搜索? –

+0

学校作业,日志应该是一个列表,每个条目都应该是一个数组,我应该实现一个二进制搜索方法来查找并从日志中提取条目,我应该能够编辑,添加和删除条目。 –

0

创建一个条件,其中(例如)then使拆除和else进行调整。调整可以通过搜索,复制,删除原稿,编辑副本并插入后者来完成。

相关问题