ループがありforeach
、最後の項目が から選択されたときに何らかのロジックを実行する必要がありますList
。例:
foreach (Item result in Model.Results)
{
//if current result is the last item in Model.Results
//then do something in the code
}
for ループとカウンターを使用せずに、どのループが最後かを知ることはできますか?
ベストアンサー1
最後の要素に対して何か別のことをするのではなく、最後の要素に対して何かを実行する必要がある場合は、LINQ を使用すると役立ちます。
Item last = Model.Results.Last();
// do something with last
最後の要素で何か違うことをする必要がある場合は、次のようなものが必要になります。
Item last = Model.Results.Last();
foreach (Item result in Model.Results)
{
// do something with each item
if (result.Equals(last))
{
// do something different with the last item
}
else
{
// do something different with every item but the last
}
}
ただし、アイテムが によって返されたアイテムと同じであることを確認するには、カスタム比較子を作成する必要があるでしょうLast()
。
このアプローチは、コレクションを反復処理する必要がある可能性があるため、注意して使用する必要がありますLast
。これは、小さなコレクションでは問題にならないかもしれませんが、コレクションが大きくなるとパフォーマンスに影響する可能性があります。また、リストに重複した項目が含まれている場合も失敗します。このような場合は、次のような方法の方が適切かもしれません。
int totalCount = result.Count();
for (int count = 0; count < totalCount; count++)
{
Item result = Model.Results[count];
// do something with each item
if ((count + 1) == totalCount)
{
// do something different with the last item
}
else
{
// do something different with every item but the last
}
}