简体   繁体   中英

Extract Number from string arrays

I have a string array and those includes different types of strings and I would like to separate those values in 2 different arrays.

string[] arr = { "12" , "34-2-2" , "xyz" , "33" , "56-3-4" , "45-4" }

Now I want linq query which gives me "12" , "33" in one and "34-2-2" , "56-3-4" in other array. Rest of the values will be ignored.

var _cust= DbContext.Customer.AsQueryable();

This will contain Id (Int32) and in this I want to add query which return if the customer has "12" , "33" will return that result.

var _cont = DbContext.Contacts.AsQueryable();

This will contain DisplayId (string) and in this I want to add query which return if the customer has "34-2-2" , "56-3-4" will return that result.

How can I write linq query for this?

You can use linq with regex pretty simply to solve this...

string[] arr = {"12", "34-2-2", "xyz", "33", "56-3-4", "45-4"};

var first = arr.Where(v => Regex.IsMatch(v, @"^\d+$")).ToArray();
var second = arr.Where(v => Regex.IsMatch(v, @"^\d+-\d+-\d+$")).ToArray();

Console.WriteLine(string.Join(" ", first));
Console.WriteLine(string.Join(" ", second));

在此处输入图片说明

Here is a solution that does what you described. It does not use Regex.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp3
{
    class Program
    {
        static readonly char[] digits = "0123456789".ToCharArray();
        static void Main(string[] args)
        {
            string[] arr = { "12", "34-2-2", "xyz", "33", "56-3-4", "45-4" };
            var pair = ProcessInput(arr);
            Console.WriteLine(String.Join(", ", pair.Item1));
            Console.WriteLine(String.Join(", ", pair.Item2));
            var done = Console.ReadLine();
        }
        static Tuple<string[], string[]> ProcessInput(string[] input)
        {
            var l1 = new List<string>();
            var l2 = new List<string>();   
            foreach(var item in input)
            {
                if (ContainsOnlyIntegers(item))
                {
                    l1.Add(item);
                    continue; // move on.
                }
                var parts = item.Split('-');
                if (parts.Length == 3 && parts.All(part => ContainsOnlyIntegers(part)))
                {
                    //must have 3 parts, separated by hypens and they are all numbers.                    
                    l2.Add(item);
                }
            }
            return Tuple.Create(l1.ToArray(), l2.ToArray());
        }

        static bool ContainsOnlyIntegers(string input)
        {
            return input.ToCharArray().All(r => digits.Contains(r));
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM