How to create an identity column within a lambda? - linq

How can I make the expression add a counter (ID) that is 1,2,3,4 etc... ? I just want to have some unqiue key to identify the data
var query = data.Select(x =>
new DemoItemV1
{
Id = x.Field<double>("ID"),
AreaId = x.Field<int>("1Area ID"),
CategoryTitle = x.Field<string>("2Table Title")
}).ToList();

I don't think you can do this purely in a Linq-to-Sql or Linq-to-Entities query. But, since you're already materializing it to a list, you can do this:
var query = data.Select(x =>
new DemoItemV1
{
AreaId = x.Field<int>("1Area ID"),
CategoryTitle = x.Field<string>("2Table Title")
})
.AsEnumerable()
.Select((x, i) => { x.ID = i + 1; return x })
.ToList();

Related

How to get all the fields after groupby in LINQ

I have this object
With Fecha="Julio2017" I have 2 items and I need to group these three items by SubcontratistaId and Fecha.
item1.Realizado=4060.000 and item2.Realizado=-4060.000 So I need to show in Julio2017 the value of 0
So I try this
private IEnumerable<SubcontratacionesEnFecha> GetRealizadosEnFecha(string proyectoId)
.....
return realizadosAbonadosEnFechaAcumulados
.GroupBy(x => new { x.SubcontratistaId, x.Fecha })
But now I don't know how to get the values of all the items grouped
If I try this I get error
If I try this
return realizadosAbonadosEnFechaAcumulados
.GroupBy(x => new { x.SubcontratistaId, x.Fecha })
.Select(x=>x.First())
.ToList();
I get this
That is, I get the first value of the items grouped
Any idea Please?
Thanks
GroupBy returns IGrouping<,>, which has Key and itself is IEnumerable<> of grouped items. So more probable usage is:
return realizadosAbonadosEnFechaAcumulados
.GroupBy(x => new { x.SubcontratistaId, x.Fecha })
.Select(g => new
{
g.Key.SubcontratistaId,
g.Key.Fecha,
Items = g.ToList()
})
.ToList();
I Found this way
var agrupacion = from p in realizadosAbonadosEnFechaAcumulados
group p by new { p.SubcontratistaId, p.Fecha } into grupo
select grupo;
foreach (var grupo in agrupacion)
{
foreach (var objetoAgrupado in grupo)
{
resultAgrupado.Add(new SubcontratacionesEnFecha
{
SubcontratistaId = objetoAgrupado.SubcontratistaId,
NombreSubcontratista= objetoAgrupado.NombreSubcontratista,
ProyectoId = objetoAgrupado.ProyectoId,
Fecha = objetoAgrupado.Fecha,
Mes = objetoAgrupado.Mes,
Año = objetoAgrupado.Año,
Realizado = objetoAgrupado.Realizado,
Planificado = objetoAgrupado.Planificado
});
}
}
return resultAgrupado;

Dynamic where clause with two entity

I need a filter between two entity.
Have two tables 1.User 2.Product
Product map with the User table.
I am going to create a dynamic where filter.
I need to find out all the users which have 'test' product.
Conditions: if userFilter count is 0 then I need all test product with the respected user.
If userFilter is there and productFilter is there then below code is working but if userFilter is not there and productFilter is there then it returning 0 row. How can I find the users which have test product? ?
Here is my Code.
public IHttpActionResult GetFilter()
{
var userFilters = new List<Filter>()
{
new Filter { PropertyName = "Username" ,
Operation = Op .Equals, Value = "Karan" },
};
var productfilter = new List<Filter>()
{
new Filter { PropertyName = "Name" ,
Operation = Op .Equals, Value = "Test product" }
};
Func<User, bool> deleg = x => true;
Func<Product, bool> delegProduct = x => true;
if (userFilters.Count > 0)
{
deleg = ExpressionBuilder.GetExpression<User>(userFilters).Compile();
}
if (productfilter.Count > 0)
{
delegProduct = ExpressionBuilder.GetExpression<Product>(productfilter).Compile();
}
var resultt = _localmarketEntities.Users.Where(deleg)
.Select(x => new
{
x.Id,
x.Username,
Product = x.Products.Where(delegProduct).Select(y => new
{
y.Id,
y.Name
}).ToList()
})
.ToList();
return Ok(resultt);
}
if i understand correct, you need all users that have test product when userFiler count is 0.
List<User> res;
var user = _localmarketEntities.Users.Where(deleg).ToList();
if (user.Count == 0) {
res = _localmarketEntities.Products.Where(delegProduct).Select(q => new User() {
Id = q.Id,
Username = q.Username,
Product = q
}).ToList();
}
else {
res = _localmarketEntities.Users.Where(deleg)
.Select(x => new
{
x.Id,
x.Username,
Product = x.Products.Where(delegProduct).Select(y => new
{
y.Id,
y.Name
}).ToList()
})
.ToList();
}

How to get EF Framework to generate this group by query

I tried a few different ways and I am not impressed with the generated output query. It seems so inefficient. It needs to be efficient and shouldn't bring back all the rows into the app layer
select year(datetaken) as yr,
month(datetaken) as mth,
day(datetaken) as dy,
count(*) as totalpics
from photos
where photos.dateTaken <= #cutoffdate
group by year(datetaken), month(datetaken), day(datetaken)
order by yr asc, mth asc, dy asc
LINQ query:
var query = ctx.Photos.Where(p => p.DateTaken <= maxCutOffDate)
.GroupBy(p => new { p.DateTaken.Year, p.DateTaken.Month, p.DateTaken.Day })
.Select(grp => grp);
var results = query.ToList();
Select only the grouping key (grp.Key):
var query = ctx.Photos.Where(p => p.DateTaken <= maxCutOffDate)
.GroupBy(p => new { p.DateTaken.Year, p.DateTaken.Month, p.DateTaken.Day })
.Select(grp => grp.Key);
var results = query.ToList();
Edit
Or, including the count of totalpics:
var query = ctx.Photos.Where(p => p.DateTaken <= maxCutOffDate)
.GroupBy(p => new { p.DateTaken.Year, p.DateTaken.Month, p.DateTaken.Day })
.Select(grp => new
{
Date = grp.Key,
TotalPics = grp.Count()
});
var results = query.ToList();
You can access the key properties through grp.Key and the count through grp.Count().
var query = ctx.Photos.Where(p => p.DateTaken <= maxCutOffDate)
.GroupBy(p => new { p.DateTaken.Year, p.DateTaken.Month, p.DateTaken.Day })
.Select(grp => new
{
grp.Key.Year,
grp.Key.Month,
grp.Key.Day,
Count = grp.Count()
});
var results = query.ToList();

Trying to set property in a LINQ GroupBy Select using a loop

I have the following code:
public class Report
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Sales { get; set; }
}
var result = myItems.GroupBy(x => new { Id = x.Id, Name = x.Name }).Select(x => new Report { Id = x.Key.Id, Name = x.Key.Name });
foreach (var item in result)
{
item.Sales = anotherColletion.FirstOrDefault(x => x.Id == item.Id).Sales;
}
I am unable to set the sales property to any value this way. Even if I try:
foreach (var item in result)
{
item.Sales = 50;
}
However, if I set the property using the following code it works:
var result = myItems.GroupBy(x => new { Id = x.Id, Name = x.Name }).Select(x => new Report { Id = x.Key.Id, Name = x.Key.Name, Sales = 50 });
Is this by design?
The problem is that LINQ queries are lazy ("deferred execution"). You are setting the property on each result of the query in the foreach loop, but these results will essentially disappear into thin air.
When you enumerate the results of the query again after your foreach (which you haven't shown us), the query is re-executed and the results recreated, effectively undoing your changes. Remember that the query is just a specification for how to produce the results, not the results themselves.
A simple fix is to materialize the query into a collection first.
var result = myItems.GroupBy(x => new { Id = x.Id, Name = x.Name })
.Select(x => new Report { Id = x.Key.Id, Name = x.Key.Name })
.ToList();
Your foreach will then end up mutating the elements of an in-memory collection rather than the results of a lazy query, and will therefore be visible downstream.
Personally though, consider setting the property in the query itself:
var result = myItems.GroupBy(x => new { Id = x.Id, Name = x.Name })
.Select(x => new Report
{
Id = x.Key.Id,
Name = x.Key.Name,
Sales = anotherCollection.First(a => a.Id == x.KeyId)
.Sales
});
Thomas,
The var results you are using is just a query, when you iterate over it, in the foreach loop, you are generating a new report object but it is not 'stored' anywhere.
Add the ToArray() or ToList() to the end of the query to fix the issue:
var result = myItems.GroupBy(x => new { Id = x.Id, Name = x.Name }).Select(x => new Report { Id = x.Key.Id, Name = x.Key.Name }).ToList();
Amir.

LINQ Join and GroupJoin

I have a list of objects, those objects may or may not have contact info:
// Join contact
query = query.Join(
(new ContactRepository(this.Db)).List().Where(x => x.IsMainContact),
x => new { x.ListItem.ContentObject.LoginId },
y => new { y.LoginId },
(x, y) => new ListItemExtended<ListItemFirm>
{
City = y.City,
State = y.State,
Country = y.Country
});
This does inner join on 'LoginId'. But I need an outter join so that if contact info does not exists for a given LoginId it will be empty.
Please help
thanks
You should execute outer join manually:
var contacts = (new ContactRepository(this.Db)).List();
query.Select(item =>
{
var foundContact = contacts.FirstOrDefault(contact => contact.Id == item.Id);
return new ListItemExtended<ListItemFirm>()
{
Id = item.Id,
City = foundContact != null ? foundContact.City : null,
State = foundContact != null ? foundContact.State : null,
Country = foundContact != null ? foundContact.Country : null,
};
})
But remember that if your Contact item is struct - checking for null isn't proper way. Use Any() operator instead of FirstOrDefault().

Resources