简体   繁体   English

将数字拆分为字符串数组

[英]split a number into an array of strings

There is a list of candidates. 有候选人名单。

candid: {12,14,16,19,25,64,78}

Code : 代码:

    for (int i = 0; i < candid.Count; i++)
    {
        var searchTerm = candid[i].ToString();
        var searchItems = searchTerm.ToCharArray().ToString();
        foreach (Tran b in transactions)
        {
            string[] temp = new string[b.itemsUtilities.Count];
            int j = 0;
            foreach (ItemUtility c in b.itemsUtilities)
            {
                temp[j] = c.item.ToString();
                j = j + 1;
            }
            if (searchItems.All(a => temp.Contains(a)))
                arraye[i] = arraye[i] + (b.transactionUtility);
        }
    }

I receive the following error: 我收到以下错误:

'string[]' does not contain a definition for 'Contains' and the best extension method overload 'Queryable.Contains(IQueryable, char)' requires a receiver of type 'IQueryable' 'string []'不包含'Contains'的定义,最佳扩展方法重载'Queryable.Contains(IQueryable,char)'需要类型为'IQueryable'的接收器

If code changed from : var searchItems = searchTerm.ToCharArray().ToString(); 如果代码从以下内容更改为: var searchItems = searchTerm.ToCharArray().ToString();

To : var searchItems = searchTerm.split(); 到: var searchItems = searchTerm.split();

This error is fixed, But this split command does not separate numbers. 此错误已修复,但是此split命令不会分隔数字。

I guess you want to separate the numbers into a string[] . 我猜您想将数字分成一个string[]

var searchItems = searchTerm.ToCharArray().ToString();

This will always create a single string "System.Char[]" so is not what you want. 这将始终创建单个字符串"System.Char[]"因此不是您想要的。

I guess you want: 我想你要:

string[] searchItems = searchTerm.Select(c => c.ToString()).ToArray();

This should fix the compiler error because searchItems.All will now project strings and not chars. 这应该可以解决编译器错误,因为searchItems.All现在将投影字符串而不是char。

More that a simple missing include, I do think that you are over thinking 一个简单的遗漏还包括更多,我确实认为您已经考虑过了

your code seems to be simplify as : 您的代码似乎简化为:

for (int i = 0; i < candid.Count; i++)
{
    var searchTerm = candid[i].ToString();

    foreach (Tran b in transactions)
    {       
        var tmp = b.itemsUtilities.Select(x=> x.item.ToString()).ToList(); 

        if( searchTerm.All(a=> tmp.Contains (a)){
            arraye[i] = arraye[i] + (b.transactionUtility);
        }
    }
}

And you can simplify again instead of for each you filter Trasanction based on the if condition. 而且,您可以再次简化,而不是根据if条件对每个过滤器进行过滤。 And if your candid is 11 no need to check twice for 1 so a simple Distinct() will help here. 而且,如果您的候选资格是11,则无需为1进行两次检查,因此,一个简单的Distinct()将在这里有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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