使用LINQ to从字符串列表中提取整数 [英] Using LINQ to extract ints from a list of strings

查看:120
本文介绍了使用LINQ to从字符串列表中提取整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表与LT;串> ,其中一些字符串是数字。我想这个子集提取到列表与LT; INT>

I have a List<string>, and some of these strings are numbers. I want to extract this subset into a List<int>.

我已经在相当冗长寻找办法做到了这一点 - 如下 - 但我得到的感觉,必须有一个整洁LINQ的方式来组织这一点。 ?任何想法

I have done this in quite a verbose looking way - as below - but I get the feeling there must be a neater LINQ way to structure this. Any ideas?

List<string> myStrs = someListFromSomewhere;
List<int> myInts = new List<int>();

foreach (string myStr in myStrs)
{
    int outInt;
    if (int.TryParse(myStr, out outInt))
    {
        myInts.Add(outInt);
    }
}



很显然,我没有的需求解决这个 - 这是主要是针对我的LINQ教育

Obviously I don't need a solution to this - it's mainly for my LINQ education.

推荐答案

您可以做到这样的:

int parsed = 0;

myInts = myStrs.Where(x => int.TryParse(x, out parsed)).Select(x => parsed);

这工作,因为LINQ运营商的执行被延迟,这意味着:结果
。对于在其中,执行,并将结果写入解析<在 myStrs 第一代码的每个项目/ code>。如果的TryParse 返回真正选择中的代码被执行。这整个代码运行下一个项目之前,这整个一个项目的代码运行。

This works because the execution of LINQ operators is deferred, meaning:
For each item in myStrs first the code in Where is executed and the result written into parsed. And if TryParse returned true the code in Select is executed. This whole code for one item runs before this whole code is run for the next item.

这篇关于使用LINQ to从字符串列表中提取整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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