C# 如何检查列表中是否已存在项目? for(int i=0;i1) { newText.Insert(0,string.Empty); newText.Insert(0,ExtractLinks.FilteredLinks[i]); newText.Insert(0,日期时间列表[i]); 新文本插入(0,t[i]); } 其他的 { 新增(t[i]); newText.Add(dateTimeList[i]); newText.Add(ExtractLinks.FilteredLinks[i]); newText.Add(string.Empty); } } }
我通过timer tick事件多次调用这个for循环。 第一次,变量t(C# 如何检查列表中是否已存在项目? for(int i=0;i1) { newText.Insert(0,string.Empty); newText.Insert(0,ExtractLinks.FilteredLinks[i]); newText.Insert(0,日期时间列表[i]); 新文本插入(0,t[i]); } 其他的 { 新增(t[i]); newText.Add(dateTimeList[i]); newText.Add(ExtractLinks.FilteredLinks[i]); newText.Add(string.Empty); } } },c#,.net,C#,.net,我通过timer tick事件多次调用这个for循环。 第一次,变量t(List)包含43项。 而列表新文本包含172项 我想检查t的任何项是否已存在于newText中,不要将其再次添加到newText中 我想问题是我正在循环使用t.Count,我还应该以某种方式循环使用newText? 如何修复它以使条件正常工作?如果您使用的框架版本允许您使用系统。Linq您可以使用Any()扩展: for (int i = 0; i < t.Count; i++) { if (!newText
List
)包含43项。
而列表新文本
包含172项
我想检查t
的任何项是否已存在于newText
中,不要将其再次添加到newText
中
我想问题是我正在循环使用t.Count
,我还应该以某种方式循环使用newText
?
如何修复它以使条件正常工作?如果您使用的框架版本允许您使用
系统。Linq
您可以使用Any()
扩展:
for (int i = 0; i < t.Count; i++)
{
if (!newText.Contains(t[i]))
{
if (firsttime > 1)
{
newText.Insert(0, string.Empty);
newText.Insert(0, ExtractLinks.FilteredLinks[i]);
newText.Insert(0, dateTimeList[i]);
newText.Insert(0, t[i]);
}
else
{
newText.Add(t[i]);
newText.Add(dateTimeList[i]);
newText.Add(ExtractLinks.FilteredLinks[i]);
newText.Add(string.Empty);
}
}
}
如果在t
中也找到了newText
的一个成员,则扩展名将返回true
编辑:事后想一想,您可能可以使用.Except()
扩展更优雅地执行此操作,但我建议您在尝试任何真正的优化之前以简单的方式完成此操作
编辑2:
newText.Any(r => t.Contains(r));
static void Main(字符串[]args)
{
var t=new List();//以43项开始
var newText=new List();//以172项开始
t、 AddRange(Enumerable.Range(1,43.Cast());
newText.AddRange(Enumerable.Range(1172.Cast());
//仅添加集合newText中不存在的成员t(添加44..172)
newText.AddRange(t.Except(newText));
}
您只需添加项目,然后使用
static void Main(string[] args)
{
var t = new List<string>(); // starts with 43 items
var newText = new List<string>(); // starts with 172 items
t.AddRange(Enumerable.Range(1, 43).Cast<string>());
newText.AddRange(Enumerable.Range(1, 172).Cast<string>());
// add only members t that do not exist in set newText (44..172 added)
newText.AddRange(t.Except(newText));
}
你试过用HashSet代替List吗?如果
newText
和t
都是List,那么复杂性是O(N*N)
。我不会用这个。
yourList.Distinct().ToList();