LEFT OUTER JOIN in LINQ

Question

How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause? Correct problem: For inner join is easy and I have a solution like this
List innerFinal = (from l in lefts from r in rights where l.Key == r.Key
                             select new JoinPair { LeftId = l.Id, RightId = r.Id})
but for left outer join I need a solution. Mine is something like this but it's not working
List< JoinPair> leftFinal = (from l in lefts from r in rights
                             select new JoinPair { 
                                            LeftId = l.Id, 
                                            RightId = ((l.Key==r.Key) ? r.Id : 0
                                        })
where JoinPair is a class:
public class JoinPair { long leftId; long rightId; }

Answer

As stated on: 101 LINQ Samples - Left outer join
var q =
    from c in categories
    join p in products on c equals p.Category into ps
    from p in ps.DefaultIfEmpty()
    select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };
Source

LINQ equivalent of foreach for IEnumerable

Question

I'd like to do the equivalent of the following in LINQ, but I can't figure out how:
IEnumerable items = GetItems();
items.ForEach(i => i.DoStuff());
What is the real syntax?

Answer

1. LINQ is all about query data, while ForEach method is about manipulation (cause side effects)! 2. There is no ForEach extension for IEnumerable; only for List. So you could do
items.ToList().ForEach(i => i.DoStuff());
Alternatively, write your own ForEach extension method:
public static void ForEach(this IEnumerable enumeration, Action action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}
Source

Retrieving Property name from lambda expression

Question

Is there a better way to get the Property name when passed in via a lambda expression?

Answer

Here's an update to method proposed by Cameron. The first parameter is not required.
public PropertyInfo GetPropertyInfo(
    Expression> propertyLambda)
{
    Type type = typeof(TSource);

    MemberExpression member = propertyLambda.Body as MemberExpression;
    if (member == null)
        throw new ArgumentException(string.Format(
            "Expression '{0}' refers to a method, not a property.",
            propertyLambda.ToString()));

    PropertyInfo propInfo = member.Member as PropertyInfo;
    if (propInfo == null)
        throw new ArgumentException(string.Format(
            "Expression '{0}' refers to a field, not a property.",
            propertyLambda.ToString()));

    if (type != propInfo.ReflectedType &&
        !type.IsSubclassOf(propInfo.ReflectedType))
        throw new ArgumentException(string.Format(
            "Expresion '{0}' refers to a property that is not from type {1}.",
            propertyLambda.ToString(),
            type));

    return propInfo;
}
Usage
var propertyInfo = GetPropertyInfo(u => u.UserID);
Source

Split List into Sublists

Question

: I believe this is another easy one for you LINQ masters out there. Is there any way I can separe a List into several separate lists of SomeObject, using the item index as the delimiter of each split? Let me exemplify: I have a List and I need a List<List> or List[], so that each of these resulting lists will contain a group of 3 items of the original list (sequentially). eg.: Original List: [a, g, e, w, p, s, q, f, x, y, i, m, c] Resulting lists: [a, g, e], [w, p, s], [q, f, x], [y, i, m], [c] I'd also need the resulting lists size to be a parameter of this function. Is it possible??

Answer

: completely lazy: works on infinite enumerables no intermediate copying/buffering O(n) execution time works also when child sequences are only partially consumed
public static IEnumerable Chunks(this IEnumerable enumerable,
                                                    int chunkSize)
{
    if (chunkSize < 1) throw new ArgumentException("chunkSize must be positive");

    using (var e = enumerable.GetEnumerator())
    while (e.MoveNext())
    {
        var remaining = chunkSize;    // elements remaining in the current chunk
        var innerMoveNext = new Func(() => --remaining > 0 && e.MoveNext());

        yield return e.GetChunk(innerMoveNext);
        while (innerMoveNext()) {/* discard elements skipped by inner iterator */}
    }
}

private static IEnumerable GetChunk(this IEnumerator e,
                                          Func innerMoveNext)
{
    do yield return e.Current;
    while (innerMoveNext());
}
Example Usage
var src = new [] {1, 2, 3, 4, 5, 6}; 

var c3 = src.Chunks(3);      // {{1, 2, 3}, {4, 5, 6}}; 
var c4 = src.Chunks(4);      // {{1, 2, 3, 4}, {5, 6}}; 

var sum   = c3.Select(c => c.Sum());    // {6, 15}
var count = c3.Count();                 // 2
var take2 = c3.Select(c => c.Take(2));  // {{1, 2}, {4, 5}}
Explanations The code works by nesting two yield based iterators. The outer iterator must keep track of how many elements have been effectively consumed by the inner (chunk) iterator. This is done by a closing over remaining with innerMoveNext(). Unconsumed elements of a chunk are discarded before the next chunk is yielded by the outer iterator. This is necessary because otherwise you get inconsistent results, when the inner enumerables are not (completely) consumed (e.g. c3.Count() would return 6). stackoverflow.com/q/419019#20953521

HOWTO: access an administrative share on a computer


If you cannot access an administrative share on a computer, apply EnableAdminShares.reg file and restart "Server" windows service.

Enjoy!

Entity Framework 7: migrations add Initial

It was changed command for initial migration

Old:
dnx ef . migration add Initial
dnx ef . migration apply

New:
dnx ef migrations add Initial
dnx ef database update
EF Core Migration details you can find here

Racklog: Kan, Ga and Roo Race

The same problem solved with more prolog style using racklog:

Three runners, Kan, Ga and Roo took part in a cross country race. Prior to the race,
four spectators from the audience, A, B, C, and D, made their prognoses, as follows:
A: Either Kan or Ga will win.
B: If Ga is the second, Roo will win.
C: If Ga is the third, Kan will not win.
D: Either Ga or Roo will be the second.

After the race, it turned out that all four statements were correct. In what order did the runners finish?
1. Kan, Ga, Roo 
2. Kan, Roo, Ga 
3. Roo, Ga, Kan 
4. Ga, Roo, Kan 
5. Impossible to determine



The Solution:

#lang racket
(require racklog)

(define %solve
  (%rel (f s t members)(
      (f s t)
     (%= members (list 'Kan 'Ga 'Roo) )
     (%member f members)
     (%member s members)
     (%member t members)
     (%and (%/== f s) (%/== f t) (%/== s t))
     (%or (%== f 'Kan) (%== f 'Ga)) ;prognose A - Either Kan or Ga will win
     (%if-then-else (%== s 'Ga) (%== f 'Roo) %true ) ;prognose B - If Ga is the second, Roo will win.
     (%if-then-else (%== t 'Ga) (%== s 'Kan) %true ) ;prognose C -  If Ga is the third, Kan will not win
     (%or (%== s 'Roo) (%== s 'Ga)) ;prognose D - Either Ga or Roo will be the second.
   )
  )
)

;find all possible solution
(%which(first second third)(%solve first second third))
(%more)


The Answer: 
'((first . Ga) (second . Roo) (third . Kan))
#f

Asterisk AST_SORCERY function

 AST_SORCERY gets a field from a sorcery object. Sorcery is always created for PJSIP aors, endpoints and identifies in asterisk. It allows y...