Tag Archive for Linq

Format a date as desired in a LINQ query assigned object

Created = String.Format("{0:M/d/yyyy}", cn.Created)

source

Simple SQL Server Diff Tool

using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Linq;

namespace Sdiff
{
    internal class Program
    {
        /// <param name = "args">arg[0] old schema connection string, arg[1] target schema connection string</param>
        /// <summary>
        ///   Tells you what to do with old schema to get it into the shape of the new
        /// </summary>
        private static void Main(string[] args)
        {
            var diffs = new List<Diff>();

            var oldContext = new IsDataContext(args[0]);
            var newContext = new IsDataContext(args[1]);

            var newTableNames = newContext.Tables.Select(x => x.Name).ToList();
            var oldTableNames = oldContext.Tables.Select(x => x.Name).ToList();

            AddDiffs(diffs, oldTableNames.Except(newTableNames), DiffKind.TableDelete);
            AddDiffs(diffs, newTableNames.Except(oldTableNames), DiffKind.TableCreate);

            var commonTableNames = newTableNames.Intersect(oldTableNames);
            foreach (var tableName in commonTableNames)
            {
                var newColumns = newContext.Columns.Where(x => x.TableName == tableName).ToList();
                var oldColumns = oldContext.Columns.Where(x => x.TableName == tableName).ToList();

                var newColumnNames = newColumns.Select(x => x.FullName);
                var oldColumnNames = oldColumns.Select(x => x.FullName);

                AddDiffs(diffs, oldColumnNames.Except(newColumnNames), DiffKind.ColumnDelete);
                AddDiffs(diffs, newColumnNames.Except(oldColumnNames), DiffKind.ColumnCreate);

                var commonColumnNames = newColumnNames.Intersect(oldColumnNames);
                foreach (var commonColumnName in commonColumnNames)
                {
                    var newDataType = newColumns.Where(x => x.FullName == commonColumnName).Select(x => x.DataType).Single();
                    var oldDataType = oldColumns.Where(x => x.FullName == commonColumnName).Select(x => x.DataType).Single();
                    if (oldDataType != newDataType) diffs.Add(new Diff(commonColumnName + " " + oldDataType + " -> " + newDataType, DiffKind.ColumnDataTypeChange));
                }
            }

            WriteSection(diffs.Where(x => x.Kind == DiffKind.TableDelete), "Tables to delete");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.TableCreate), "Tables to create");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.ColumnDelete), "Columns to delete");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.ColumnCreate), "Columns to create");
            WriteSection(diffs.Where(x => x.Kind == DiffKind.ColumnDataTypeChange), "Columns to modify");

            Console.ReadKey();
        }

        private static void AddDiffs(List<Diff> diffs, IEnumerable<string> names, DiffKind diffKind)
        {
            diffs.AddRange(names.Select(name => new Diff(name, diffKind)));
        }


        private static void WriteSection(IEnumerable<Diff> diffs, string title)
        {
            if (!diffs.Any()) return;
            Console.WriteLine();
            Console.WriteLine(title);
            Console.WriteLine(string.Empty.PadLeft(title.Length, '-'));
            foreach (var name in diffs.Select(x => x.Name).OrderBy(x => x))
            {
                Console.WriteLine(name);
            }
        }

        private class Diff
        {
            public Diff(string name, DiffKind kind)
            {
                Name = name;
                Kind = kind;
            }

            public string Name { get; private set; }
            public DiffKind Kind { get; private set; }
        }

        internal enum DiffKind
        {
            TableDelete,
            TableCreate,
            ColumnDelete,
            ColumnCreate,
            ColumnDataTypeChange
        }
    }


    public class IsDataContext : DataContext
    {
        public Table<Column> Columns;
        public Table<Table> Tables;
        public IsDataContext(string connection) : base(connection) {}
    }

    [Table(Name = "INFORMATION_SCHEMA.TABLES")]
    public class Table
    {
        [Column(Name = "TABLE_NAME")] public string Name;
    }

    [Table(Name = "INFORMATION_SCHEMA.COLUMNS")]
    public class Column
    {
        [Column(Name = "CHARACTER_MAXIMUM_LENGTH")] public int? CharacterMaximumLength;
        [Column(Name = "DATA_TYPE")] public string DataTypeName;
        [Column(Name = "COLUMN_NAME")] public string Name;
        [Column(Name = "TABLE_NAME")] public string TableName;

        public string DataType
        {
            get
            {
                if (!CharacterMaximumLength.HasValue) return DataTypeName;
                if (CharacterMaximumLength.Value == -1) return DataTypeName + "(MAX)";
                return DataTypeName + "(" + CharacterMaximumLength.Value + ")";
            }
        }

        public string FullName { get { return TableName + "." + Name; } }
    }
}

source

LINQ ForEach

using System;
using System.Collections.Generic;

namespace ForEachExample
{
    public static class Utility
    {
        public static void ForEach<T>(this IEnumerable<T> coll, Action<T> function)
        {
            IEnumerator<T> en = coll.GetEnumerator();
            while (en.MoveNext())
                function(en.Current);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var array = new int[] { 1, 2, 3 };
            //Expexted output: 123
            array.ForEach(val => Console.Write(val));
        }
    }
}

source

LINQ Extension Methods

[TestMethod]
public void DemoLINQExtensionMethods()
{
List<int> ints = new List<int>(new int[] { 1, 11, 12 });
//Standard Delegate
int val = ints.FirstOrDefault(ThisOneGoesToEleven);
Assert.IsTrue(val == 11, "Eleven was not found. Value = " + val.ToString());
//Using Anonymous Method
val = ints.FirstOrDefault(delegate(int i) { return i == 11; });
Assert.IsTrue(val == 11, "Eleven was not found. Value = " + val.ToString());
//Using equivalent Lambda syntax
val = ints.FirstOrDefault(x => x == 11);
Assert.IsTrue(val == 11, "Eleven was not found. Value = " + val.ToString());
}
private bool ThisOneGoesToEleven(int volume)
{
return volume == 11;
}

source

GetSubKeys – static function provides recursive access to registry keys with LINQ queries or foreach loops

/// <summary>
/// Given a registry key, get a list of child sub-keys.
/// This function recursively calls itself.
/// Intended to be used in an implementation of recursive enumeration in
/// either a foreach loop or a LINQ expression.
/// If access to a key is not allowed, such subkeys are not included in the list and
/// a Debug.WriteLine prints the key name.
/// <example>
/// string searchString = "dll".ToLower(); // Example search for mention of dll. 'ToLower' is used for non-case-sensisitve search.
/// Microsoft.Win32.RegistryKey keyStart = rkLm.OpenSubKey(@"SOFTWAREAdobe");
///
/// // LINQ expression to retrieve a list of strings based on the 'where' condition.
/// IEnumerable<string> regVals2 =
///    // These two 'from' clauses allow nested enumeration of keys and their values.
///    from key in GetSubKeys(keyStart)
///    from valueName in key.GetValueNames()
///    // create a string 'value' for convenient access to value.
///    let value = key.GetValue(valueName).ToString()
///    where
///        // this example where clause searches for searchString.
///        // and of course could be enhanced to narrow search results.
///        // 'ToLower' is used for non-case-sensisitve search.
///        value.ToLower().Contains(searchString) ||
///        valueName.ToLower().Contains(searchString) ||
///        key.Name.ToLower().Contains(searchString)
///    // format a string containing the key name, value name and value.
///    // Hint: call a member function here to allow setting of break points.
///    select string.Format("{0}: {1}={2}", key.Name, valueName.ToString(), value);
/// </example>
/// </summary>
/// <param name="keyParentArg">A registry key</param>
/// <returns>An IEnumerable List of subkeys under the keyParentArg.</returns>
static IEnumerable<Microsoft.Win32.RegistryKey> GetSubKeys(Microsoft.Win32.RegistryKey keyParentArg)
{
// This link... <a href="http://www.csharphelp.com/archives2/archive430.html" >http://www.csharphelp.com/archives2/archive430.html</a>
//   ...has a GetSubKeys implementation without try/catch.
//   Omitting try/catch will cause LINQ expressions to abort prematurely.
// This link... <a href="http://support.microsoft.com/kb/267908" >http://support.microsoft.com/kb/267908</a> -
//   ...has an example that enumerates using advapi32.dll without .NET or LINQ.
// This link... <a href="http://blog.domaindotnet.com/2008/09/08/the_fastest_dot_net_hash_set_collection_with_linq_extended_features/" >http://blog.domaindotnet.com/2008/09/08/the_fastest_dot_net_hash_set_collection_with_linq_extended_features/</a>
//   ...has an alternative implementation (using GetAllSubkeys and TryOpenSubKey) that
//   I thought was more complex than necessary for simple registry enumeration. This
//   GetSubKeys function provides similar functionality with one function.

// This list will be built as subkeys are added.
List<Microsoft.Win32.RegistryKey> keysFound = new List<Microsoft.Win32.RegistryKey>();

try
{
if (keyParentArg.SubKeyCount > 0)
{
foreach (string strKeyChild in keyParentArg.GetSubKeyNames())
{
try
{
Microsoft.Win32.RegistryKey keyChild = keyParentArg.OpenSubKey(strKeyChild);
if (keyChild != null)
{
keysFound.Add(keyChild);

// Recursive call back into this method
IEnumerable<Microsoft.Win32.RegistryKey> keyGrandChildren = GetSubKeys(keyChild);

if (keyGrandChildren != null)
{
keysFound.AddRange(keyGrandChildren);
}
else
{
System.Diagnostics.Debug.Assert(false);
}
} // if not null.
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message + Environment.NewLine + " failed trying " + strKeyChild + " in " + keyParentArg);
}
} // foreach
} // if
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message + Environment.NewLine + " failed trying " + keyParentArg);
}

return keysFound;
} // GetSubKeys()

source

Force immediate evaluation of LINQ expression using .ToArray()

IEnumerable<string> windowsFiles = System.IO.Directory.GetFiles(Environment.GetEnvironmentVariable("SystemRoot"), "*.INF", System.IO.SearchOption.AllDirectories);

IEnumerable<string> files =
(
from f in windowsFiles
where System.IO.File.ReadAllText(f).Contains(searchText)
select System.IO.Path.GetFileNameWithoutExtension(f)
).ToArray(); // ToArray forces immediate evaluation.

source

LINQ Conditional Sum

MyList.Where(x => x.Product == "Apple").Sum(x => x.TotalSales)

source

LINQ Conditional Count

MyList.Count(x => x.Product == "Apple")

source

Linq in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataClasses1DataContext dc = new DataClasses1DataContext();
var benutzerListe = from ds in dc.Benutzers where ds.PLY=="33" select ds;
foreach (var item in benutzerListe)
{
Console.WriteLine(item.Vorname + " " + item.Nachname);
item.Vorname = "Rolf";

}

Benutzer bn = new Benutzer() { ID = "3", Nachname = "sdfs", PLY = "saf", Strasse = "dsf", Vorname = "dsfs", Wohnort = "dsf" };


dc.Benutzers.InsertOnSubmit(bn);
dc.SubmitChanges();
Console.ReadKey();
}
}
}

source