[英]how to get the last result after looping at C#
你好,我是 C# 和編程的新手,所以我卡住了幾個小時才能從我的循環結果中獲得最后的結果,我的代碼:
using System;
public class Program
{
public static void Main()
{
string merek = string.Empty;
// i wanted to get the last value which is 13 R DLX DG M/T
string str = "DAIHATSU.ALL NEW XENIA.13 R DLX DG M/T";
// Taking a string
char[] spearator = { '.', '.' };
// using the method
String[] strlist = str.Split(spearator);
foreach(String s in strlist)
{
Console.WriteLine(s);
}
}
}
這一點
the result is
DAIHATSU
ALL NEW XENIA
13 R DLX DG M/T
// i wanted to get the last value which is 13 R DLX DG M/T
string str = "DAIHATSU.ALL NEW XENIA.13 R DLX DG M/T";
我真的很感激任何幫助謝謝。
您可以使用IEnumerable<T>.Last()
:
var last = strlist.Last();
請記住包括 Linq:
using System.Linq;
你不需要for
循環。 您可以使用以下命令簡單地打印最后一部分:
Console.WriteLine(strlist[strlist.Length - 1]);
根據您的標題問題,您正在尋找循環后的最后一個值。
您可以直接從字符串數組訪問它。
strlist[strlist.Length - 1];
如果有任何正當理由通過數組,另一種選擇是這個
string latest = "";
foreach(String s in strlist)
{
Console.WriteLine(s);
latest = s;
}
// After the loop, the latest variable will have the value you are looking for.
為了避免使用另一個 Linq cal,您可以嘗試使用來自 Jon Skeet 的舊但可靠的 MiscUtil 的 SmartEnumerable 擴展中的“IsLast”屬性。 這是現代 .net 端口的鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.