简体   繁体   中英

Extract the last element and add it to the end in list by changing a property value

I have a list like this

CustomerSearch.cs

int id;
string searchedWord;

If for example, if this result is like this

[
 {id: 1, searchedWord :"test"}
 {id: 2, searchedWord: "news"}
]

I am trying to copy the last element in the list and append to the existing list and increment the id number value.

The expected result is

[
 {id: 1, searchedWord :"test"}
 {id: 2, searchedWord: "news"}
 {id: 3, searchedWord: "news"}
]

I could do this way

CustomerSearch customerSearch=new CustomerSearch();
customerSearch.Id=result.ElementAt(result.Count()-1).Id;
customerSearch.SearchedWord=result.ElementAt(result.Count()-1).SearchedWord;

List<CustomerSearch> newResult=new List<CustomerSearch>();
foreach(var mycustomerSearch in result)
{
 newResult.Add(mycustomerSearch);
}
newResult.Insert(1, customerSearch);
newResult.ElementAt(2).Id=3;

I don't think, this is the optimal way, if there is a better way to do this, please share it, thanks. We can create the expected result as a new list or with that existing list.

Assuming you may modify the original list result :

CustomerSearch customerSearch = new CustomerSearch {
  Id = result.Last().Id + 1,
  SearchedWord = result.Last().SearchedWord
};

result.Add(customerSearch);

If you may not modify result :

CustomerSearch customerSearch = new CustomerSearch {
  Id = result.Last().Id + 1,
  SearchedWord = result.Last().SearchedWord
};

List<CustomerSearch> newResult = result.Select(x => x).ToList();

newResult.Add(customerSearch);

Note that Last() throws an exception if result is null or empty. To protect against this, the above operation should be preceded by a check for those cases:

if (results == null || !results.Any())
{
  // handle in some way, perhaps by returning.
}
  • Use Linq Any() to check if result is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM