![](/img/trans.png)
[英]C# FirstOrDefault() not working even with using System.Linq
[英]C# How to use FirstOrDefault with an array while unable to have System.Linq in the namespace?
當我在 IDE 中測試時,此處提供的代碼有效,但將使用此代碼的軟件本身並沒有給我using System.Linq
聲明的可能性。 我一直試圖弄清楚如何使用它,否則我將不得不回到一個我寧願不使用的解決方案,因為它的准確率較低。
問題在這里
var stringMatch = sArray.FirstOrDefault(titleID.Contains);
我不確定如何正確提供參考資料。 我認為它應該是System.Linq.Enumerable
的方式......但這是我第一次處理這樣的問題,所以非常感謝任何幫助。
string TakeEndPeriod = "";
string NewEndPeriod = "";
string FindEndSpace = "";
string GetEndPeriod = "";
string titleID = "document for the period ended December 31 2014";
string s1 = "ended ";
string s2 = "Ended ";
string s3 = "Ending ";
string[] sArray = new [] { s1, s2, s3};
var stringMatch = sArray.FirstOrDefault(titleID.Contains);
if (stringMatch != null)
{
TakeEndPeriod = titleID.Substring(titleID.LastIndexOf(stringMatch));
FindEndSpace = TakeEndPeriod.Substring(TakeEndPeriod.IndexOf(" "));
GetEndPeriod = FindEndSpace.Substring(1);
string[] formatArray = new[] { "dd MMMM yyyy", "MMMM dd yyyy" };
DateTime ModEndPeriod;
if (!DateTime.TryParseExact(GetEndPeriod,
formatArray,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out ModEndPeriod))
{
//parsing failed
}
NewEndPeriod = ModEndPeriod.ToString("yyyy-MM-ddT00:00:00Z");
編輯:
我收到的錯誤消息:
'System.Array' does not contain a definition for 'FirstOrDefault' and no extension
method 'FirstOrDefault' accepting a first argument of type 'System.Array' could be
found (are you missing a using directive or an assembly reference?)
編輯:
這是我從管理軟件的開發人員支持那里得到的解決方案:
String Title = "document for the period Ending December 31 2014";
Match M = Regex.Match(Title, ".*?(?i)(ended|ending)(.*)");//Case insensitive search for "ended" and "ending"
if (M.Groups.Count == 3)
{
//Match OK
DateTime DT = DateTime.Parse(M.Groups[2].Value);
//The variable DT will now have the parsed date.
Console.WriteLine(DT.ToString("yyyyMMdd"));
}
不允許我聲明'使用System.Linq'。
由於Enumerable.FirstOrDefault
是一個擴展方法,您還可以使用它的完全限定類名System.Linq.Enumerable
:
var stringMatch = System.Linq.Enumerable.FirstOrDefault(sArray, s => titleID.Contains(s));
甚至更短:
var stringMatch = System.Linq.Enumerable.FirstOrDefault(sArray, titleID.Contains);
請注意,擴展方法只是一個靜態方法,這就是為什么有效。
您可以自己實現FirstOrDefault
或從參考源中獲取它:
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null) throw ArgumentException("source");
if (predicate == null) throw ArgumentException("predicate");
foreach (TSource element in source)
{
if (predicate(element))
return element;
}
return default(TSource);
}
避免 linq 並使用數組作為第一個或默認值的最簡單方法是 Array.Find(array, predicate);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.