Потеря обработчиков событий после использования LINQ

Есть ObservableCollection<string> mystrings, которой я на старте приложения присваиваю значения, и делаю обработчик события mystrings.CollectionChanged += mystrings_OnChange;

Однако дальше мне нужно сделать выборку из этой коллекции, отсеить ненужные элементы, и удалить их из коллекции. Однако когда я делаю

mystrings = new ObservableCollection<string>(mystrings.Where(x => x ...)); 

То после этого у меня mystrings новый обьект, который “потерял” обработчики событий. Как правильнее с этим бороться?

SkipLast of an IEnumerable – Linq Extension

As my answer to this question, I came up with this solution:

static public IEnumerable<T> SkipLast<T>(this IEnumerable<T> data, int count) {   if (data == null || count < 0) yield break;    Queue<T> queue = new Queue<T>(data.Take(count));    foreach (T item in data.Skip(count))   {     queue.Enqueue(item);     yield return queue.Dequeue();   } } 

It returns all items in the set but the count last, but without knowing anything about the size of the data set. I think it’s funny and that it’s working, but a comment claims that is doesn’t. Am I overlooking something?


A version with a circular queue could be:

static public IEnumerable<T> SkipLast<T>(this IEnumerable<T> data, int count) {   if (data == null || count < 0) yield break;   if (count == 0)   {     foreach (T item in data)       yield return item;   }   else   {     T[] queue = data.Take(count).ToArray();     int index = 0;      foreach (T item in data.Skip(count))     {       index %= count;       yield return queue[index];       queue[index] = item;       index++;     }   } } 

Performance wise they seems to be even.


Compared to other solutions like the most obvious:

data.Reverse().Skip(count).Reverse() 

it seems to be at least as fast and for very large set about twice as fast.

Test case:

  int count = 20;   var data = Enumerable.Range(1, count);    for (int i = 0; i < count + 5; i++)   {     Console.WriteLine($  "Skip: {i} => {(string.Join(", ", data.SkipLast1(i)))}");   } 

Any comments are useful.

Obtener la descripción de un Enum en una consulta linq

Trabajo con C#, Visual Studio 2019 Tengo la siguiente consulta

var result = from ov in context.OrdenVentas                          join c in context.Clientes on ov.ClienteId equals c.ClienteId                          where                              (filter.Codigo == null || ov.CodigoNumerico.Contains(filter.Codigo))                              &&                              (!filter.ClienteId.HasValue || ov.ClienteId.Equals(filter.ClienteId.Value))                              &&                              (filter.FechaEmision == null || ov.FechaEmision >= filter.FechaEmision)                              &&                              (filter.FechaCaducidad == null || ov.FechaCaducidad <= filter.FechaCaducidad)                              &&                              ov.Estado == EstadoOrdenVenta.Emitido                          select                              new UniversalExtend()                              {                                  Id = ov.OrdenVentaId,                                  NumeroComprobante = ov.NumeroComprobante,                                  Descripcion = c.RazonSocial,                                  FechaEmision = ov.FechaEmision,                                  FechaCaducidad = ov.FechaCaducidad,                                  Estado =                                   Total = ov.Total                              };             return result.ToList(); 

En estado necesito obtener la descripción de un enum.

En el campo estado(en la db) tengo los valores del enum ahora quiero recuperarlo en una variable estado de tipo string, ¿como puedo leer la descripcion de un enum pasandole un campo ov.Estado el cual tiene el id del enum?

public enum EstadoOrdenVenta : int {     [Description("EMITIDO")]     Emitido = 1,     [Description("APROBADO")]     Aprobado = 2,     [Description("ATENDIDO")]     Atendido = 3 } 

Solo quiero obtener lo que esta en minúscula.

Filtros condicionales usando linq

Trabajo con C#, Visual Studio 2019 Tengo la siguiente query

using (var context = new BusinessContext())         {             var result = from ov in context.OrdenVentas                          join c in context.Clientes on ov.ClienteId equals c.ClienteId                          where ov.Estado == EstadoOrdenVenta.Emitido &&                              (filter.Codigo == null || ov.CodigoNumerico.Contains(filter.Codigo))                              &&                              (!filter.ClienteId.HasValue || ov.ClienteId.Equals(filter.ClienteId.Value))                              &&                              (filter.FechaEmision == null || ov.FechaEmision >= filter.FechaEmision)                              &&                              (filter.FechaCaducidad == null || ov.FechaCaducidad <= filter.FechaCaducidad)                          select                              new UniversalExtend()                              {                                  Id = ov.OrdenVentaId,                                  NumeroComprobante = ov.NumeroComprobante,                                  Descripcion = c.RazonSocial,                                  FechaEmision = ov.FechaEmision,                                  FechaCaducidad = ov.FechaCaducidad,                                  EstadoId = ov.Estado,                                  Total = ov.Total                              };             return result.ToList();         } 

En el filtro debo agregarle un parámetro de estado el cual es emitido pero si no le mando nada me trae a todos los emitidos, si es que no le mando nada no me debe de mostrar nada. ¿Como debería hacerlo?

Saludos!

Перевести sql запрос в LINQ

Есть часть запроса SQL

24 * SUM(ISNULL(CAST(time_op AS float), 0)) AS t_regl 

,где time_op имеет тип DateTime. Мне нужно эту строчку реализовать с помощью linq

Я делала так:

Sum  = 24 * gg.Sum(z =>z.time_op == null ? "01.01.1900 0:00:00" : z.time_op) 

естественно это не работает и куча ошибок с преобразованиями. Помогите sql переделать в linq

System.InvalidOperationException(An exception was thrown while attempting to evaluate a LINQ query parameter expression)

I don’t know what’s wrong with my LINQ query, everything looks fine but I got above error on the following code: if (!dbcontext.AndroidUser.Any(user => user.Equals(value.UserName))) Here’s my complete code for RegisterController.cs.

 using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using System.Threading.Tasks;  using APITesting.Models;  using APITesting.Utils;  using Microsoft.AspNetCore.Mvc;  using Newtonsoft.Json;   namespace APITesting.Controllers  {  [Route("api/[controller]")]  public class RegisterController : Controller  { NoNameRestaurantContext dbcontext = new NoNameRestaurantContext();  // POST api/<controller> [HttpPost] public string Post([FromBody]AndroidUser value) {     //First we need to check that user is existing in database.     if (!dbcontext.AndroidUser.Any(user => user.Equals                (value.UserName)))     {         AndroidUser user = new AndroidUser();         user.UserName = value.UserName;         user.Hash = Convert.ToBase64String(Common.GetRandomHash(16));         user.Password = Convert.ToBase64String(Common.HashPassword(             Encoding.ASCII.GetBytes(value.Password),             Convert.FromBase64String(user.Hash)));          //Save to Database          try         {             dbcontext.Add(user);             dbcontext.SaveChanges();             return JsonConvert.SerializeObject("Register Successfully");         }         catch (Exception ex)         {             return JsonConvert.SerializeObject(ex.Message);         }     }     else     {         return JsonConvert.SerializeObject("User is existing in Database");     }    }   }  } 

and for Common.cs class that I used to convert my password to hashPassword.

 using System;  using System.Collections.Generic;  using System.Linq;  using System.Security.Cryptography;  using System.Threading.Tasks;   namespace APITesting.Utils  {  public class Common  { /*  *   * FUNCTION TO CREATE RANDOM HASH STRING  *   */ public static byte[] GetRandomHash(int length) {     var random = new RNGCryptoServiceProvider();     byte[] hash = new byte[length];     random.GetNonZeroBytes(hash);     return hash; } /*  *   * FUNCTION TO CREATE PASSWORD WITH HASH  *   */ public static byte[] HashPassword(byte[] password, byte[] hash) {     HashAlgorithm algorithm = new SHA256Managed();     byte[] plainTextWithHashByte = new byte[password.Length + hash.Length];     for (int i = 0; i < password.Length; i++)     {         plainTextWithHashByte[i] = password[i];     }     for (int i = 0; i < hash.Length; i++)     {         plainTextWithHashByte[password.Length + i] = hash[i];     }     return algorithm.ComputeHash(plainTextWithHashByte);   }  } } 

I am following this tutorial: https://www.youtube.com/watch?v=b6T0_j7I9CE

Contains en consulta LINQ

teniendo una consulta que busca por títulos de películas en una base de datos, quiero sacar las que coincidan con el criterio de búsqueda introducido mediante un input de tipo text. Para ello uso un Contains con la variable busqueda que almacena dicho patrón.

 var peliculaConsulta = from Peliculas in dbDatos.Peliculas                                    join TipoPelicula in dbDatos.TipoPelicula                                     on Peliculas.idTipo equals TipoPelicula.IdTipo                                    where Peliculas.Titulo.Contains(busqueda)                                    select new { Peliculas.Titulo, Peliculas.TipoPelicula, TipoPelicula.Tipo };                   <table>                     <thead>                         <tr>                              <th>Título</th>                             <th>País</th>                             <th>Tipo de película</th>                          </tr>                     </thead>                 </table>              foreach (var elemento in peliculaConsulta)             {                     <td>@elemento.Titulo</td><td>@elemento.TipoPelicula</td><td>@elemento.Tipo</td>               } 

Al presentarlo por pantalla me muestra lo siguiente:

introducir la descripción de la imagen aquí

Muchas gracias de antemano.

Refactoring a LINQ lambda expression to eliminate duplicate object creation code

the following code fetches data from a MySql database to generate a simple report on accrued work time on projects.

I’ve been away from Entity Framework for a while and looking at this code you can see that the creation of ListProject is basically repeated 3 times.

Is there any way to refactor this so I can reuse the duplicate parts?

I’ve thought about a factory method, but that won’t work because it can’t be translated to SQL by the expression interpreter.

    var project = entities.Tickets         .Where(p => p.ID == id)         .Select(p => new ListProject         {             Id = p.ID,             Name = p.ueberschrift,             AssignedEmployee = new ListEmployee             {                 Id = p.AssignedEmployee.ID,                 Name = p.AssignedEmployee.name             },             WorkUnits = p.WorkUnits                 .Select(wu => new ListProjectWorkUnit                 {                     Duration = wu.dauer,                     PauseDuration = wu.pauseDauer,                     Employee = new ListEmployee                     {                         Id = wu.AssignedEmployee.ID,                         Name = wu.AssignedEmployee.name                     }                 })                 .ToList()             })             .Single(); 
    project.Tickets = entities.Tickets         .Where(p => p.vonProjekt == id)         .Where(p => p.phaseID == 0)         .OrderBy(p => p.ueberschrift)         .Select(p => new ListProject         {             Id = p.ID,             Name = p.ueberschrift,             AssignedEmployee = new ListEmployee             {                 Id = p.AssignedEmployee.ID,                 Name = p.AssignedEmployee.name             },             WorkUnits = p.WorkUnits                 .Select(wu => new ListProjectWorkUnit                 {                     Duration = wu.dauer,                     PauseDuration = wu.pauseDauer,                     Employee = new ListEmployee                     {                         Id = wu.AssignedEmployee.ID,                         Name = wu.AssignedEmployee.name                     }                 })                 .ToList()             })             .Single(); 
    project.Phases = entities.projekt_phase         .Where(p => p.projektID == id)         .OrderBy(p => p.rang)         .Select(p => new ListProjectPhase         {             Id = p.ID,             Name = p.name,             Tickets = p.Tickets                 .OrderBy(t => t.ueberschrift)                 .Select(t => new ListProject                 {                     Name = t.ueberschrift,                     Id = t.ID,                     AssignedEmployee = new ListEmployee                     {                         Id = t.AssignedEmployee.ID,                         Name = t.AssignedEmployee.name                     },                     WorkUnits = t.WorkUnits                         .Select(wu => new ListProjectWorkUnit                         {                             Duration = wu.dauer,                             PauseDuration = wu.pauseDauer,                             Employee = new ListEmployee                             {                                 Id = wu.AssignedEmployee.ID,                                 Name = wu.AssignedEmployee.name                             }                         })                         .ToList()                 })                 .ToList()         })         .ToList(); 

LINQ Where clause from array of strings

I have a list of class Products:

class Products {     public string Name { get; set; }     public string Size { get; set; }     public string ProductId { get; set; }     public string Category { get; set; } } 

I would like to use one TextBox to search through any matching products utilizing a wildcard value. This would return me a list of items where all values in the search string are found somewhere in the four properties listed above.

As of now, I’m using string[] values = searchText.Split("*".ToCharArray) to seperate the values of the search string into an array of strings (based on an asterisk wildcard). From there, I get stumped, since I want to search for all values of the search string in all properties of the class.

I tried to figure it out using a complex LINQ statement, but I have not been able to figure it out how to make this work. I don’t know how to build a Where statement when I don’t know how many values I’m going need to test against my four properties.