包含两个元素的列表

本文关键字:列表 元素 包含两 | 更新日期: 2023-09-27 18:24:25

我有一个列表

 public List<string[]> UList = new List<string[]>();
 UList.Add(new string[] { "veeru", "basanti" });
 UList.Add(new string[] { "jay", "radha" });
 UList.Add(new string[] { "gabbar", "ramlal" });

如果"veeru"answers"basanti"这对存在,我该如何在列表中搜索?我想要类似的东西

 if(pair exists)
    // do this
 else
    // do that

包含两个元素的列表

如果您正在寻找完全匹配:

var values = new [] { "veeru", "basanti" };
if(UList.Any(x => values.SequenceEqual(x))) { }

否则:

var values = new [] { "veeru", "basanti" };
if(UList.Any(x => values.All(x.Contains))) { }

如果您的唯一任务是快速确定您的集合是否包含某对,请考虑使用Tuple<string, string>HashSet。它明显快于List的实现。

var set = new HashSet<Tuple<string, string>>();
set.Add(new Tuple<string, string>("veeru", "basanti"));
set.Add(new Tuple<string, string>("jay", "radha"));
set.Add(new Tuple<string, string>("gabbar", "ramlal"));
if (set.Contains(new Tuple<string, string>("veeru", "basanti")))
{
    ....
}

这将起作用。

     if (UList.Any(x => x[0] =="veeru" && x[1] == "basanti"))
     {
     }
     else
     {
     }

在这种情况下,使用KeyValuePair<string, string>:

public List<KeyValuePair<string, string>> UList = new List<KeyValuePair<string, string>>();
private void button2_Click(object sender, EventArgs e)
{
    UList.Add(new KeyValuePair<string, string>("veeru", "basanti"));
    UList.Add(new KeyValuePair<string, string>("jay", "radha"));
    UList.Add(new KeyValuePair<string, string>("gabbar", "ramlal"));
}
private void button1_Click_1(object sender, EventArgs e)
{
    string KEY = "jay";
    string VALUE = "radha";
    if(UList.Contains(new KeyValuePair<string,string>(KEY,VALUE)))
        MessageBox.Show("YES");
    else
        MessageBox.Show("NO");
}