max date record in LINQ

Starting from .NET 6 MaxBy LINQ method is available. var result = items.MaxBy(i => i.Date); Prior to .NET 6: O(n): var result = items.Aggregate((x, y) => x.Date > y.Date ? x : y); O(n log n): var result = items.OrderByDescending(i => i.Date).First(); O(n) – but iterates over the sequence twice: var max = items.Max(i => …

Read more

The source contains no DataRows

ds.Tables[4] might have rows, but the result of your LINQ query might not, which is likely where the exception is being thrown. Split your method chaining to use interim parameters so you can be dead certain where the error is occurring. It’ll also help you check for existing rows using .Any() before you call CopyToDataTable() …

Read more

Linq – Top value from each group

My answer is similar to Yuriy’s, but using MaxBy from MoreLINQ, which doesn’t require the comparison to be done by ints: var query = from player in players group player by player.TeamName into team select team.MaxBy(p => p.PlayerScore); foreach (Player player in query) { Console.WriteLine(“{0}: {1} ({2})”, player.TeamName, player.PlayerName, player.PlayerScore); } Note that I’ve changed …

Read more

Edit specific Element in XDocument

With using System.Xml.Linq; it becomes var doc = XElement.Load(fileName); var saveGame = doc .Element(“savegames”) .Elements(“savegame”) .Where(e => e.Element(“IdNumber”).Value == “2”) .Single(); saveGame.Element(“balance”).Value = “50”; doc.Save(fileName);