Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

c# - Trying to filter only digits in string array using LINQ

I'm trying to filter only digits in string array. This works if I have this array: 12324 asddd 123 123, but if I have chars and digits in one string e.g. asd1234, it does not take it. Can u help me how to do it ?

int[] result = input
            .Where(x => x.All(char.IsDigit))// tried with .Any(), .TakeWhile() and .SkipWhile()
            .Select(int.Parse)
            .Where(x => x % 2 == 0)
            .ToArray();
question from:https://stackoverflow.com/questions/65640845/trying-to-filter-only-digits-in-string-array-using-linq

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this should work. The function digitString will select only digits from the input string, and recombine into a new string. The rest is simple, just predicates selecting non-empty strings and even numbers.

var values = new[]
{
    "helloworld",
    "hello2",
    "4",
    "hello123world123"
};

bool isEven(int i) => i % 2 == 0;
bool notEmpty(string s) => s.Length > 0;
string digitString(string s) => new string(s.Where(char.IsDigit).ToArray());

var valuesFiltered = values
    .Select(digitString)
    .Where(notEmpty)
    .Select(int.Parse)
    .Where(isEven)
    .ToArray();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...