Achmad Darmawan
Achmad Darmawan

Reputation: 31

get last data from looping in c#

I have the code for looping. and I need the latest data from the results of the looping. and from the last iteration, I just want to take the value "KodePosition" only. so how to get it? The following code example looping. please help me for this solution. thank you

foreach (string data in splitRow)
{
 string[] splitData = data.Split(';');
 DataRow dr = dt.NewRow();
 dr["KodePosition"] = splitData[0];
 dr["NamaPosition"] = splitData[1];
 dr["UserLogin"] = splitData[2];
 dt.Rows.Add(dr);
}

Upvotes: 0

Views: 73

Answers (3)

codebased
codebased

Reputation: 7073

ASSUMING HERE THAT THE SPLITROW IS OF LIST TYPE.

If you want last row and then the position column then you can use this approach.

        var lastRow = splitRow.Last();
        var lastPosition = lastRow.Split(';').First();

Make sure you have using System.Linq.

Upvotes: 1

miltonb
miltonb

Reputation: 7355

Declare the outside the scope of the foreach a variable to store the "KodePosition" and set that for each update in the loop. Something like this

var lastKodePosition;
foreach (string data in splitRow)
{
 string[] splitData = data.Split(';');
 DataRow dr = dt.NewRow();
 dr["KodePosition"] = splitData[0]; 
 lastKodePosition = dr["KodePosition"];
 dr["NamaPosition"] = splitData[1];
 dr["UserLogin"] = splitData[2];
 dt.Rows.Add(dr);
}

Upvotes: 1

Jeffrey Wieder
Jeffrey Wieder

Reputation: 2376

If you are just trying to retrieve the value from the last row:

string lastKodePositionValue = dt.Rows[dt.Rows.Count-1]["KodePosition"];

If this is not what you are looking to do, please be more specific.

Upvotes: 3

Related Questions