在没有foreach的情况下检查列表中项目的条件 [英] Checking an condition on an item in a list without 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 theforeach
loop, you do not have much more choices than afor
loop. This way (I assumemylist
is anIList
):
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 meanList<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屋!