简体   繁体   English

从C#4.0中的元组列表中查找和删除元组

[英]find and delete tuple from list of tuples in C# 4.0

I have created a list of tuples: 我创建了一个元组列表:

static List<Tuple<string, string>> Alt;

The user adds to this list: 用户添加到此列表:

Alt.Add(new Tuple<string, string>(tbAlt.Text, ""));

What is the best way to find a Tuple based on the first string (ie the tbAlt.Text ) and either delete it or modify the second string? 基于第一个字符串(即tbAlt.Text)找到元组并删除它或修改第二个字符串的最佳方法是什么?

I am new to using Tuples and lists :) 我是新手使用元组和列表:)

Many thanks for any help! 非常感谢您的帮助!

Your list of tuples looks much like dictionary. 你的元组列表看起来很像字典。 Consider using it instead - Dictionary<string,string> . 考虑使用它 - Dictionary<string,string> It already has methods for retreiving value by key, deleting it, etc 它已经有了通过密钥检索值,删除它等的方法

If there could be multiple values for the same key, you can use Lookup class. 如果同一个键可能有多个值,则可以使用Lookup类。

It appears the first string must be unique or you would not find a (singular) 看来第一个字符串必须是唯一的或者你找不到(单数)

Why are you using List<Tuple<string, string>> ? 你为什么使用List<Tuple<string, string>>

Why not Dictionary<string,string> ? 为什么不是Dictionary<string,string>

Dictionary<TKey, TValue>.ContainsKey is very very fast. Dictionary<TKey, TValue>.ContainsKey非常快。

Dictionary.ContainsKey Dictionary.ContainsKey

You could use List<T>.FindIndex to find the matching index, then replace as needed. 您可以使用List<T>.FindIndex查找匹配的索引,然后根据需要进行替换。

int index = Alt.FindIndex(t => t.Item1 == tbAlt.Text);

if (index != -1)
{
   // Modify
   Alt[index] = Tuple.Create(tbAlt.Text, "NewText");

   // Remove:
   Alt.RemoveAt(index);
}

Find tuple based on value of first string ( Item1 ): 根据第一个字符串( Item1 )的值查找元组:

var t = Alt.FirstOrDefault(i => i.Item1 == "SomeString");
if(t != null)
{
    // delete
    Alt.Remove(t);
}

From comments: 来自评论:

You can't modify value of second item ( Item2 ), because tuples are immutable, so you 'll have to remove it and add it again. 您无法修改第二项( Item2 )的值,因为元组是不可变的,因此您必须将其删除并再次添加。

If you are sure the list contain your item : 如果您确定该列表包含您的项目:

Alt.Remove(Alt.First(i => i.Item1 == tbAlt.Text));

However, in order to modify a Tuple, you must create a new one. 但是,要修改元组,必须创建一个新元组。

if (Alt.Any(i => i.Item1 == tbAlt.Text))
{
    Alt.Remove(Alt.First(i => i.Item1 == tbAlt.Text));
    Alt.Add(new Tuple<string, string>(tbAlt.Text, "Something New"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM