如何检查列表中是否包含C#中的另一个列表项 [英] how to check that a list contains another list item in C#
本文介绍了如何检查列表中是否包含C#中的另一个列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,
如何查找字符串已经存在于列表中。例如,如果我想写数据,我现在有一个包含数据的列表在这期间,我希望保持一个条件是否该字符串已经存在于列表中。我使用下面的代码,但它不工作,你可以帮助我
Hello,
How to find a string is already present in a list.For example i have a list that contains data now if i want to write the data in to another list during this i want to keep a condition whether the string is already present in the list.I am using the below code but its not working can you kindly help me
List<list><string>> Messlist
List<string> val= new List<string>();
if (!(Messlist.Contains(val)))
{
---
}
推荐答案
尝试LINQ -
Try LINQ -
var result = Messlist
.Where(x=> x.Contains(searchString));
你的问题是val
是另一个List但是包含
期望a字符串
要查看一个列表是否包含另一个列表中的值,请使用List<t>.Intersect [ ^ ]方法并检查计数任何
属性
Eg
Your problem is thatval
is another List butContains
expects astring
To see if one list contains the values in another use the List<t>.Intersect[^] method and check against theCountAny
property
E.g.
private void button1_Click(object sender, EventArgs e)
{
var l1 = new List<string> {"1", "2", "3", "4", "5", "6"};
var l2 = new List<string> { "4", "5"};
var l3 = new List<string> {"7", "8"};
ListCheck(l1, l2);
ListCheck(l1, l3);
}
private static bool ListCheck<T>(IEnumerable<T> l1, IEnumerable<T> l2)
{
// TODO: Null parm checks
if (l1.Intersect(l2).Any())
{
Console.WriteLine("matched");
return true;
}
else
{
Console.WriteLine("not matched");
return false;
}
}
或更改 val
是一个字符串
这是一个很好的例子。
试试这个
http:// www.dotnetperls.com/intersect [ ^ ]
http://stackoverflow.com / questions / 7187996 / intersect-two-list-in-c-sharp [ ^ ]
Here is some good example for you.
Try this
http://www.dotnetperls.com/intersect[^]
http://stackoverflow.com/questions/7187996/intersect-two-list-in-c-sharp[^]
这篇关于如何检查列表中是否包含C#中的另一个列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文