Querying using LINQ and the Entity Framework

When using the Entity Framework and if you want to query using LINQ, this is how it is done:

Make sure to have your Context set up. My context is ListofRestaurantsContext, and my table name is List_Of_Restaurants
context.TableName.SqlQuery

Raw SQL Query: (Dangerous)


                using (var context = new ListofRestaurantsContext())
                {
                    var blogs = context.List_Of_Restaurants.SqlQuery("Select * from List_Of_Restaurants").ToList();
                    foreach (var test1 in blogs)
                    {
                        var assasa = test1.Address;
                    }
                    var test3 = "";

                }

Using simple “where”:

context.TableName.Where(n => n.Name == “Blah”);

  using (var context = new ListofRestaurantsContext())
                {
                    var blogs = context.List_Of_Restaurants.Where(n => n.restaurant_id == 1).ToList();
                    foreach (var test1 in blogs)
                    {
                        var assasa = test1.Address;
                    }
                    var test3 = "";

                }

Replace Specific Words in C#

I’ve been working on a decent size project and I have been learning a lot of new things that I thought I’d share with you guys. This will go over how to replace specific words using Regex in C#. For example if your string contains “Let’s add this pizza because adding pizza is a fad,” if you use normal removal tools such as string.Replace(“add”, “”) it would make the string “Let’s this pizza because ing pizza is a.”

Obviously, we don’t want that to happen, so the best tool to use is boundary.

What is a Boundary?
There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

Source: http://www.regular-expressions.info/wordboundaries.html

In simple words, boundary allows you to set it so that you only replace the word that has the string you want. You can use something simple such as String.Replace(@”\badd\b”, “”).

Remember to place

using System.Text.RegularExpressions;

on the top of your class/form.

I came up with a nice little class to remove a specific word:

    public static class LetsDoThis
    {
        public static string ReplaceWords(this string variable, string findit, string getridofit, bool findspecificword)
        {
            string finding_the_text= findspecificword? string.Format(@"\b{0}\b", findit) : findit;
            return Regex.Replace(variable, finding_the_text, getridofit);
        }
    }