HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Update first and last item in List<T>

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itemlastupdatefirstandlist

Problem

I am trying to do the following. I have a list of Custom objects:

public class TestObject {
  public int Id { get; set; }
  public string Name { get; set; }
  public bool First { get; set; }
  public bool Last { get; set; }
}


I want to set the property First and Last to true at the first and last item in the list.

Side note: I am filling the list in a LinqToEntity query. Perhaps its even possible in LinqToEntity.

I have come up with the following but i doubt its the most efficient way.

var result = new List {
   new TestObject { Id = 1, Name = "Test1" },
   new TestObject { Id = 2, Name = "Test2" },
   new TestObject { Id = 2, Name = "Test2" }
};

foreach (var item in result) 
{
   item.First = result.FirstOrDefault() == item;
   item.Last = result.LastOrDefault() == item;
}


I eventually want to display the results in a ASP.Net's ListView (webforms), where I have buttons that will be displayed based on the property.

Is there an easier or more efficient way of doing this?

Solution

The performance of your current code depends a little about the implementation of the list, but what I primarily would have done is to extract first and last to variables that get initialized once, not in each iteration.

var first = result.FirstOrDefault();
var last = result.LastOrDefault();
foreach (var item in result) 
{
   item.First = first == item;
   item.Last = last == item;
}


Secondly, if you're sure that all initial items have false at both the First and Last properties, then you don't need to use a loop at all, just do something like this:

if (result.Any())
{
    result.First().First = true;
    result.Last().Last = true;
}


I am no C# expert but this should give you an idea.

However, I'd question why you have the First and Last properties in the first place. Are you really really sure that you need them as properties? It feels to me that there's a risk that they will be inconsistent with their actual position in the list. And if you have access to the list itself where you want to get the value of the First/Last properties, well then you don't need the properties at all, do you?

Code Snippets

var first = result.FirstOrDefault();
var last = result.LastOrDefault();
foreach (var item in result) 
{
   item.First = first == item;
   item.Last = last == item;
}
if (result.Any())
{
    result.First().First = true;
    result.Last().Last = true;
}

Context

StackExchange Code Review Q#55340, answer score: 14

Revisions (0)

No revisions yet.