Deutsch
Germany.ruФорумы → Архив Досок→ Программирование

Подскажите по чату ГПТ

03.03.23 22:25
Re: Подскажите по чату ГПТ
 

или вот вопрос:

Can you write a generic function in c#, which gets a entity type and lambda condition and returns a list of elements, that meet a condition

Ответ

public static List<T> GetEntities<T>(Func<T, bool> condition) where T : class

{

using (var context = new YourDbContext())

{

return context.Set<T>().Where(condition).ToList();

}

}


Вопрос

Can you rewrite this function to return only one property of the entity. This property is passed to function as expression

Ответ


public static List<TResult> GetEntities<T, TResult>(Func<T, bool> condition, Expression<Func<T, TResult>> selector)

where T : class

{

using (var context = new YourDbContext())

{

return context.Set<T>()

.Where(condition)

.Select(selector)

.ToList();

}

}

 

Перейти на