Posts

Showing posts with the label LINQ

Simple file content summary

A few days ago, I was reviewing some old samples to teach C# and I came across one that instructed the user to write a simple program. The goal was to read a text file and display on the Console a small summary containing, for example, the number of characters and the number of lines. The solution provided for this exercise was to iterate over the content of the file character by character and increment a few counters based of Char.IsSomething tests. Here is a much cooler way to do that using a LINQ query : string content = File.ReadAllText(path); var contentByGroups = from c in content group c by Char.GetUnicodeCategory(c) into groups select new { Category = groups.Key, Count = groups.Count() }; foreach (var group in contentByGroups) { Console.WriteLine("Category {0} : {1}", group.Category, group.Count); } The Char.GetUnicodeCategory is used to get the corresponding category of each character of the ...

Get newly added entities in an Entity Framework query

A few days ago, a colleague of mine ran into a little problem using Entity Framework. He was adding new entities to the context and then wanted to display these entities. Unfortunately, since the new entities are only in memory, they are not fetched by the query. In fact, you have to use the ObjectStateManager accessible from the context to query in-memory entities. This object manages the entity cache in the context. You can use the following code to obtain every entity already in the cache. Assuming the type of the objects you want to query is Client : var listInMemory = context.ObjectStateManager .GetObjectStateEntries(EntityState.Added) .Select(e => e.Entity).OfType<Client>().ToList(); listInMemory will contain only the new added entities from the current context. You can combine EntityState values to retrieve entities in different states. You can also use an Union construct to add those entities to the list of entities returned by a standard Entity que...