簡體   English   中英

Linq錯誤:“string []不包含'Except'的定義。”

[英]Linq error: “string[] does not contain a definition for 'Except'.”

這是我的代碼:

    public static string[] SplitKeepSeparators(this string source, char[] keptSeparators, char[] disposableSeparators = null)
    {
        if (disposableSeparators == null)
        {
            disposableSeparators = new char[] { };
        }

        string separatorsString = string.Join("", keptSeparators.Concat(disposableSeparators));
        string[] substrings = Regex.Split(source, @"(?<=[" + separatorsString + "])");

        return substrings.Except(disposableSeparators); // error here
    }

我得到編譯時錯誤string[] does not contain a definition for 'Except' and the best extension method overload ... has some invalid arguments

我已經在源文件的頂部包含了using System.Linq

怎么了?

您的substrings變量是一個string[] ,但disposableSeparatorschar[] - 並且Except適用於兩個相同類型的序列。

disposableSeparators更改為string[] ,或使用以下內容:

return substrings.Except(disposableSeparators.Select(x => x.ToString())
                 .ToArray();

注意對ToArray()的調用 - Except只返回一個IEnumerable<T> ,而聲明你的方法返回一個string[]

你的問題是你使用.Except<T>(this IEnumerable<T> source, IEnumerable<T> other)有兩種不同類型的T( stringchar )。 如果要使用“除外”,請將分隔符更改為字符串數組。

https://msdn.microsoft.com/en-us/library/vstudio/bb300779%28v=vs.100%29.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM