Найдите первый файл, который соответствует использованию шаблона PowerShell

Первое, что нужно сделать состоит в том, чтобы поставить вход, для наблюдения, какой TSQL был сгенерирован; например:

ctx.Log = Console.Out;

LINQ к SQL, кажется, рассматривает, аннулирует немного несовместимо (в зависимости от литерала по сравнению со значением):

using(var ctx = new DataClasses2DataContext())
{
    ctx.Log = Console.Out;
    int? mgr = (int?)null; // redundant int? for comparison...
    // 23 rows:
    var bosses1 = ctx.Employees.Where(x => x.ReportsTo == (int?)null).ToList();
    // 0 rows:
    var bosses2 = ctx.Employees.Where(x => x.ReportsTo == mgr).ToList();
}

, Таким образом, все, что я могу предложить, является использованием хорошая форма с пустыми указателями!

т.е.

Expression<Func<Category,bool>> predicate;
if(categoryId == null) {
    predicate = c=>c.ParentId == null;
} else {
    predicate = c=>c.ParentId == categoryId;
}
var subCategories = this.Repository.Categories
           .Where(predicate).ToList().Cast<ICategory>();
<час>

Обновление - я получил его работающий "правильно" использование пользовательского Expression:

    static void Main()
    {
        ShowEmps(29); // 4 rows
        ShowEmps(null); // 23 rows
    }
    static void ShowEmps(int? manager)
    {
        using (var ctx = new DataClasses2DataContext())
        {
            ctx.Log = Console.Out;
            var emps = ctx.Employees.Where(x => x.ReportsTo, manager).ToList();
            Console.WriteLine(emps.Count);
        }
    }
    static IQueryable<T> Where<T, TValue>(
        this IQueryable<T> source,
        Expression<Func<T, TValue?>> selector,
        TValue? value) where TValue : struct
    {
        var param = Expression.Parameter(typeof (T), "x");
        var member = Expression.Invoke(selector, param);
        var body = Expression.Equal(
                member, Expression.Constant(value, typeof (TValue?)));
        var lambda = Expression.Lambda<Func<T,bool>>(body, param);
        return source.Where(lambda);
    }
49
задан Peter Mortensen 11 July 2015 в 11:23
поделиться

1 ответ

You can force PowerShell into returning an array, even when only one item is present by wrapping a statement into @(...):

@(gci *.xls)[0]

will work for each of your three cases:

  • it returns the first object of a collection of files
  • it returns the only object if there is only one
  • it returns $null of there wasn't any object to begin with

There is also the -First parameter to Select-Object:

Get-ChildItem -Filter *.xls | Select-Object -First 1
gci -fi *.xls | select -f 1

which works pretty much identical to the above, except that the list of files doesn't need to be enumerated completely by Get-ChildItem, as the pipeline is aborted after the first item. This can make a difference when there are many files matching the filter.

95
ответ дан 7 November 2019 в 11:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: