在没有foreach的情况下检查列表中项目的条件 [英] Checking an condition on an item in a list without foreach

查看:67
本文介绍了在没有foreach的情况下检查列表中项目的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用foreach的情况下检查列表中项目的条件。例如,而不是必须这样做:

  foreach 字符串 [] item   mylist)
{
if (Convert.ToBoolean(item [ 0 ]){}
}



我可以访问mylist的项目直接。我怎样才能实现这个目标?



谢谢!

解决方案

首先,没有办法您将在列表中找到与条件匹配的第一个项目,或者列表中所有项目与迭代匹配某些条件:使用Linq将只是自动化对你来说。



你在这里澄清的问题是你想要的究竟是什么从你的字符串列表的迭代中返回:



1.列表中可转换为bool值的字符串列表?



2.或者,只是一堆o f列表中的布尔值:没有索引,很难想象使用它。



3.或者,为每个执行一些操作(执行一些代码)可以根据布尔值和/或字符串列表中该值的索引转换为bools的字符串? imho,一个更合理的用例。



4.在上面的帖子中看到我对你需要澄清的其他内容的评论



我将在这里给你一个例子,将字符串列表作为字典返回< int,bool> ...其中'key是列表中布尔值的索引,值是转换后的布尔值。

  //   required  
使用 System.Linq

// 假设这里的数据源是一个简单的List< string>
List< string> strList = new List< string>
{
True False True 臭氧 错误
};

// 此变量必须初始化在此处显示的Linq中使用
bool booltest = false ;

字典< int,bool> dctIntBool = strList
。选择((str,index)= > new {index, str})
.Where(pair = > Boolean .TryParse(pair.str, out booltest))
.ToDictionary(pair = > pair.index,pair = < span class =code-keyword>> booltest);

注意Linq的变体'Select,它创建/保留它迭代的集合的索引在这里使用:每对index / value被投射到一个新的匿名结构中;然后,Where Linq语句过滤那些对,因此任何字符串不能转换为'bool的对被丢弃;最后,Linq ToDictionary用于创建Dictionary结构,对于每个KeyValuePair的值,使用Where子句中的'tryParse语句'分配给'booltest的布尔值。


如果你想迭代一个集合,并且不想使用 foreach 循环,你没有比更多的选择循环。这种方式(我假设 mylist 是一个 IList ):

  int  count = mylist.Count; 
string [] result; // 这假设你有一个IList< string []>
for int i = 0 ; i < count; i ++)
{
result = mylist [i];
bool value = Convert.ToBoolean(result [ 0 ]);
}



我看不出为什么要使用字符串数组列表来获取布尔值的原因。显然必须有更好/更清洁的实施。



希望这会有所帮助。祝你好运。


如果你的意思是 List< T> ,你可以使用 List.Contains方法 [ ^ ]。



< pre lang =c#> List< string> mylist = new 列表< string>(){ cat dog bird};

var result = mylist.Contains( );
Console.WriteLine( 列表{0}'鸟'字,结果= = true 包含:< span class =code-string>
不包含);


How can I check for a condition on an item in a list without using foreach. For example, instead of having to do:

foreach(string[] item in mylist)
{
  if(Convert.ToBoolean(item[0]){}
}


I can just access mylist's item directly. How can I achieve this?

Thanks!

解决方案

First, there's no way you will locate the first item in a list that matches a condition, or, all items in a List that match some condition without iteration: using Linq will just "automate" that for you.

The question for you to clarify here is what exactly you want returned from your iteration of a list of strings:

1. a list of indexes in the list where strings convertible to bool values are ?

2. or, a just a bunch of boolean values in a list: without the indexes, hard to imagine a use for that.

3. or, to take some action (execute some code) for each string that can be converted to bools based on the boolean value and/or the index of that value in the list of strings ? imho, a more plausible use-case.

4. see my comment on your post above for what else you need to clarify

I'll show you an example here of returning the list of strings as a Dictionary<int, bool> ... where the 'key is the index of the boolean value in the list, and the value is the converted boolean value.

// required
using System.Linq

// assume the data source here is a simple List<string>
List<string> strList = new List<string>
{
    "True", "what", "False", "True", "ozone", "False"
};

// this variable must be initialized to be used in the Linq shown here
bool booltest = false;

Dictionary<int,bool> dctIntBool = strList
.Select((str, index) => new {index, str})
.Where(pair => Boolean.TryParse(pair.str, out booltest))
.ToDictionary(pair => pair.index, pair => booltest);

Note the variation of Linq 'Select that creates/preserves an index of the collection it iterates is used here: each pair of index/value is projected into a new anonymous structure; then, the Where Linq statement filters those "pairs" so any pair where the string is not convertible to 'bool is discarded; finally, Linq ToDictionary is used to create the Dictionary structure, using, for the Value of each KeyValuePair the boolean value assigned to 'booltest by the 'TryParse statement in the Where clause.


If you want to iterate over a collection, and do not want to use the foreach loop, you do not have much more choices than a for loop. This way (I assume mylist is an IList):

int count = mylist.Count;
string[] result; // This assumes you have an IList<string[]>
for (int i = 0; i < count; i++)
{
   result = mylist[i];
   bool value = Convert.ToBoolean(result[0]);
}


I cannot see the reason why you are working with a list of string-arrays to get a boolean. There must be obviously a better/cleaner implementation.

Hope this helps. Good luck.


If you mean List<T>, you may use List.Contains method[^].

List<string> mylist = new List<string>(){"cat","dog","bird"};

var result = mylist.Contains("bird");
Console.WriteLine("A list {0} 'bird' word", result==true ? "contains" : "does not contain");


这篇关于在没有foreach的情况下检查列表中项目的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆