I try to select name but there is names which is repeat now i want to select these through distinct how i done this in linq
string data2 = "[";
T1 DB = new T1();
var te = DB.tblVni;
foreach (var c in te)
{
data2 += "'" + c.Name + "',";
}
data2 = data2.Substring(0, data2.Length - 1);
data2 += "]";
this return me like this
['DPSB','MV','PSB','','','','PSB','PSB','','PSB','PSB','MV','','','MV','PSB','','MV','MV','MV','','PSB','MV',
where as i dont want to repeat these names
any solution
You could replace
foreach (var c in te)
{
data2 += "'" + c.Name + "',";
}
by the following snippet.
foreach (var c in te.Select( x => x.Name ).Distinct())
{
data2 += "'" + c + "',";
}
You could also use the existing facilities and rewrite the entire part as
T1 DB = new T1();
var te = DB.tblVni;
string data2
= String.Format("[{0}]",
String.Join( ",", te.te.Select( x => x.Name ).Distinct() ) );
which would not require the manual removal of the terminal comma. However, in total, indeed Json should not be generated manually, there are existing tools for that, like this one.
Try this
var data2 = String.Format("[{0}]", te.Select(i => i.Name).Distinct().Aggregate((v, n) => String.Format("'{0}','{1}'", v,n)));
Output:
['DPSB','MV','PSB']
Related
I'm taking a list of counts, averaging and returning all results according to the condition. Looks like my command is too erroneous. I don't know how to do it yet.
I have tables:
var qr = (from Product c in _context.Products
join o in _context.RatingProducts on c.ID equals o.IDProduct
where c.Status == true
orderby c.NumProduct
group o by c.ID into g
select new {
ProductId = g.Key,
CountID = g.Count(),
//SumID = g.Sum(s => s.StarRating).ToString(),
AveragedID = g.Count() > 0 ? g.Average(x => x.StarRating) : 0
}).ToList();
var getqr = _context.Products.Where(a => a.Status).ToList();
int count = 0;
double averaged = 0;
foreach (var item in getqr)
{
int key = item.ID;
var id = qr.Where(x => x.ProductId == key).FirstOrDefault();
if(id != null)
{
count = id.CountID;
averaged = Math.Round(id.AveragedID,1);
}
var productquery = item;
}
var query = from c in qr
join p in getqr on c.ProductId equals p.ID
select new ProductQuery
{
ID = p.ID,
IDProduct = p.IDProduct,
CategoryID = p.CategoryID,
NumProduct = p.NumProduct,
Name = p.Name,
Status = p.Status,
Price = p.Price,
PriceOld = p.PriceOld,
ContentsSmall = p.ContentsSmall,
Contents = p.Contents,
Images = p.Images,
CountID = count,
//SumID = c.SumID,
AveragedID = averaged,
};
return query.ToList();
However when I debug, it shows only one result with row ID = 1. I want to display list: count, average results of table 1. Tks.
As far as I understand you should make LEFT JOIN here, so need to add DefaultIfEmpty in the initial query, and slightly change average counting logic.
Something like this, should work:
var qr = (from Product c in _context.Products
join o in _context.RatingProducts on c.ID equals o.IDProduct into productRatings
from pr in productRatings.DefaultIfEmpty()
where c.Status == true
orderby c.NumProduct
group o by c.ID into g
select new {
ProductId = g.Key,
CountID = g.Count(),
AveragedID = g.Average(x => x == null ? 0 : x.StarRating)
}).ToList();
I want to compare my list of stocks price with my set Stoploss which is stored and once the condition trigger alert by email. Below is my code
function emailAlert()
{
var stock1nameRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Watchlist").getRange("A5");
var stock1name = stock1nameRange.getValues();
var stock1cmpRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Watchlist").getRange("B5");
var stock1cmp = stock1cmpRange.getValues();
var stock1s1Range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Watchlist").getRange("AK5");
var s1 = stock1s1Range.getValues();
var stock1s2Range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Watchlist").getRange("AL5");
var s2 = stock1s2Range.getValues();
var ui = SpreadsheetApp.getUi();
if(stock1cmp<s1)
{
if(stock1cmp<s2)
{
ui.alert( stock1name + stock1cmp + 'is less than' +s2 );
var message = stock1name + stock1cmp + 'is less than' +s2 ;
MailApp.sendEmail("#gmail.com", "Stock Watchlist alert", message)
return s2
}
else
{
ui.alert( stock1name + stock1cmp + 'is less than' +s1 );
var message = stock1name + stock1cmp + 'is less than' +s1 ;
MailApp.sendEmail("#gmail.com", "Stock Watchlist alert", message )
return s1
}
}
}
This is for single stock. How can I make it more generic and compile all the stock list which pass the condition into single mail. Thanks.
Sen
In order to be able to select all the values you will be needing a for loop.
Snippet
function emailAlert() {
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName("Watchlist");
var stockName = sheet.getRange("A5:FINAL_RANGE").getValues();
var stockCmp = sheet.getRange("B5:FINAL_RANGE").getValues();
var s1 = sheet.getRange("AK5:FINAL_RANGE").getValues();
var s2 = sheet.getRange("AL5:FINAL_RANGE").getValues();
for (var i = 0; i < stockName.length; i++) {
if (stockCmp[i][0] < s1[i][0]) {
if (stockCmp[i][0] < s2[i][0]) {
ui.alert(stockName[i][0] + stockCmp[i][0] + ' is less than ' + s2[i][0]);
var message = stockName[i][0] + stockCmp[i][0] + ' is less than ' + s2[i][0];
MailApp.sendEmail("#gmail.com", "Stock Watchlist Alert", message);
return s2[i][0];
} else {
ui.alert(stockName[i][0] + stockCmp[i][0] + ' is less than ' + s1[i][0]);
var message = stockName[i][0] + stockCmp[i][0] + ' is less than ' + s1[i][0];
MailApp.sendEmail("#gmail.com", "Stock Watchlist Alert", message);
return s1[i][0];
}
}
}
}
Explanation
The above code loops through all the values from your columns by using a for loop and then based on the conditions you set, is sending the email and alerting the user. The range is retrieved by using the getRange() method with the a1Notation parameter. The a1Notation parameter here is represented by the start and the end of the range in which you have the values you need for the script.
Note
The above script is built considering the fact that the stockName, stockCmp, s1, s2 are all associated, meaning that they all have the same number of values stored in them.
Reference
Apps Script Range Class - getValues();
Apps Script Sheet Class - getRange(a1Notation);
JavaScript For Loop.
I've this linq query:
var query = (from l in _contexto.lineasencargos
join a in _contexto.articulos on l.IDARTICULO equals a.IDARTICULO
join af in _contexto.articulofamilia on a.IDARTICULO equals af.IDARTICULO
join f in _contexto.familias on af.IDFAMILIA equals f.IDFAMILIA
join e in _contexto.encargos on l.IDENCARGO equals e.IDENCARGO
where e.FECHAHORAENCARGOS >= _finder.FechaDe &&
e.FECHAHORAENCARGOS <= _finder.FechaA &&
e.FECHAHORARECOGERENCARGOS >= _finder.FechaRecogerDe &&
e.FECHAHORARECOGERENCARGOS <= _finder.FechaRecogerA &&
e.clientes.RAZONSOCIALCLIENTE.Contains(_finder.Cliente)
group l by new { l.IDARTICULO, l.CANTIDADLINEAENCARGO,a.DESCRIPCIONARTICULO,f.DESCRIPCION,f.IDFAMILIA }
into g
select new listaEncargosAgrupados
{
IdArticulo=(int)g.Key.IDARTICULO,
DescripcionArticulo=g.Key.DESCRIPCIONARTICULO,
IdFamilia=g.Key.IDFAMILIA,
DescripcionFamilia=g.Key.DESCRIPCION,
SumaCantidad = (decimal)g.Sum(x => x.CANTIDADLINEAENCARGO),
SumaPrecio = (decimal)g.Sum(x => x.PRECIOLINEAENCARGO),
Total = (decimal)((decimal)g.Sum(x => x.CANTIDADLINEAENCARGO) * g.Sum(x => x.PRECIOLINEAENCARGO))
});
and i need create a condition in Where, that filter dynamically:
if (_finder.IdTienda > 0)
{
query = query.Where(x=>x.IDTIENDA == _finder.IdTienda);
}
But this Where it is not correct because IDTIENDA is contained in _context.encargos and not in listaEncargosAgrupados
How i can revolve this problem?
Thanks
Add e into grouping statement and IDTIENDA list into the result:
var query = (from l in _contexto.lineasencargos
join a in _contexto.articulos on l.IDARTICULO equals a.IDARTICULO
join af in _contexto.articulofamilia on a.IDARTICULO equals af.IDARTICULO
join f in _contexto.familias on af.IDFAMILIA equals f.IDFAMILIA
join e in _contexto.encargos on l.IDENCARGO equals e.IDENCARGO
where e.FECHAHORAENCARGOS >= _finder.FechaDe &&
e.FECHAHORAENCARGOS <= _finder.FechaA &&
e.FECHAHORARECOGERENCARGOS >= _finder.FechaRecogerDe &&
e.FECHAHORARECOGERENCARGOS <= _finder.FechaRecogerA &&
e.clientes.RAZONSOCIALCLIENTE.Contains(_finder.Cliente)
group new { l, e} by new { l.IDARTICULO, l.CANTIDADLINEAENCARGO,a.DESCRIPCIONARTICULO,f.DESCRIPCION,f.IDFAMILIA }
into g
select new { Result = new listaEncargosAgrupados
{
IdArticulo=(int)g.Key.IDARTICULO,
DescripcionArticulo=g.Key.DESCRIPCIONARTICULO,
IdFamilia=g.Key.IDFAMILIA,
DescripcionFamilia=g.Key.DESCRIPCION,
SumaCantidad = (decimal)g.Sum(x => x.l.CANTIDADLINEAENCARGO),
SumaPrecio = (decimal)g.Sum(x => x.l.PRECIOLINEAENCARGO),
Total = (decimal)((decimal)g.Sum(x => x.l.CANTIDADLINEAENCARGO) * g.Sum(x => x.l.PRECIOLINEAENCARGO))
},
IDTIENDAs = new HashSet<int>(from x in g
let id = x.e.IDTIENDA
where id.HasValue
select (int)id.Value)
});
...
if (_finder.IdTienda > 0)
{
query = query.Where(x => x.IDTIENDAs.Contains (_finder.IdTienda));
}
var query1 = query.Select(x => x.Result);
Finally the solution to my problem was to employ executestorequery in the context of my EF, and creat a SQL query :
List<ListaEncargosAgrupados> lista;
string queryString = #"SELECT l.IDARTICULO,a.DESCRIPCIONARTICULO,f.DESCRIPCION descripcionFamilia,f.IDFAMILIA,sum(l.CANTIDADLINEAENCARGO) sumaCantidad,avg(l.PRECIOLINEAENCARGO)
sumaPrecio,sum(l.CANTIDADLINEAENCARGO)*avg(l.PRECIOLINEAENCARGO) Total " +
"FROM lineasencargos l,articulos a,articulofamilia af,familias f,encargos e " +
"where a.IDARTICULO=l.IDARTICULO and a.IDARTICULO=af.IDARTICULO " +
"and af.IDFAMILIA=f.IDFAMILIA and l.IDENCARGO=e.IDENCARGO ";
if (_finder.IdTienda > 0)
{
queryString = queryString + " and e.idtienda=" + _finder.IdTienda;
}
queryString = queryString + " group by l.IDARTICULO,a.DESCRIPCIONARTICULO,f.DESCRIPCION,f.IDFAMILIA order by a.DESCRIPCIONARTICULO ";
var salidaQuery = _contexto.ExecuteStoreQuery<ListaEncargosAgrupados>(queryString).AsQueryable().ToList();
lista = salidaQuery;
I am getting this error when I try to join
var users = _users.Get();
var userApprovals =
(from approval in _entities.ApprovalEntities
join userDetail in users on approval.UserKey equals userDetail.UserId
where approval.EmployeeUid == employeeUid
select new UserApproval
{
Id = approval.Id,
EmployeeUid = approval.EmployeeUid,
UserKey = approval.UserKey,
UserId = approval.UserId,
UserName = userDetail.FirstName + " " + userDetail.LastName
}).ToList();
error
Only primitive types or enumeration types are supported in this context
Thanks
fixed,
var userApprovals =
(from approval in _entities.ApprovalEntities.ToList()
join userDetail in users on approval.UserKey equals userDetail.UserId
where approval.EmployeeUid == employeeUid
select new UserApproval
{
Id = approval.Id,
EmployeeUid = approval.EmployeeUid,
UserKey = approval.UserKey,
UserId = approval.UserId,
UserName = userDetail.FirstName + " " + userDetail.LastName
}).ToList();
In my case, my problem was use IEnumerable without using toList() sentence.
Look, this code show "error Only primitive types or enumeration types are supported in this context" error:
var query = db.TemplatesDocs.Where(x => x.Id_Template == idTmpl)
.Join(Utils.DocumentTypes, x => x.Id_Type, y => y.Id, (x, y) => new { tmpDoc = x, type = y } )
.ToList();
Look, this code is fixed the error:
var query = db.TemplatesDocs.Where(x => x.Id_Template == idTmpl).ToList()
.Join(Utils.DocumentTypes, x => x.Id_Type, y => y.Id, (x, y) => new { tmpDoc = x, type = y } )
.ToList();
I need to build a where clause at runtime but I need to do an OR with the where clause. Is this possible?
Here is my code. Basically "filter" is a enum Bitwise, son hence filter could be equal to more than 1 of the following. Hence I need to build up the where clause.
If I execute the WHEREs separately then imagine if I do the Untested first, and it returns 0 records that means I can't execute a where on the Tested because its now 0 records.
I will put some pseudo-code below:
string myWhere = "";
if ((filter & Filters.Tested) == Filters.Tested)
{
if (myWhere != "" ) myWhere =myWhere + "||";
myWhere = myWhere " Status == "Tested";
}
if ((filter & Filters.Untested) == Filters.Untested)
{
if (myWhere != "" ) myWhere =myWhere + "||";
myWhere = myWhere " Status == "Untested";
}
if ((filter & Filters.Failed) == Filters.Failed)
{
if (myWhere != "" ) myWhere =myWhere + "||";
myWhere = myWhere " Status == "Failed";
}
// dataApplications = a List of items that include Tested,Failed and Untested.
// dataApplication.Where ( myWhere) --- Confused here!
Is this possible?
I don't want to include lots of "IFs" because there are lots of combinations i.e. no filter, filter= tested Only, filter = Untested and Tested ... and lots more.
If you have this:
IEnumerable<MyType> res = from p in myquery select p;
You can define a
var conditions = new List<Func<MyType, bool>>();
conditions.Add(p => p.PropertyOne == 1);
conditions.Add(p => p.PropertyTwo == 2);
res = res.Where(p => conditions.Any(q => q(p)));
And now the trick to make Lists of Funcs of anonymous objects (and you can easily change it to "extract" the type of anonymous objects)
static List<Func<T, bool>> MakeList<T>(IEnumerable<T> elements)
{
return new List<Func<T, bool>>();
}
You call it by passing the result of a LINQ query. So
var res = from p in elements select new { Id = p.Id, Val = p.Value };
var conditions = MakeList(res);
var statusTexts = new List<string>(); // Add desired status texts
dataApplication.Where(item =>
statusTexts.Any(status => item.Status == status))
Use HashSet<> for statuses, then .Contains will be O(1) instead of usual O(n) for List<>:
var statuses = new HashSet<string>() {"a", "b", "c"};
var list = new[] {
new { Id = 1, status = "a"},
new { Id = 2, status = "b"},
new { Id = 3, status = "z"}
};
var filtered = list.Where(l => statuses.Contains(s => l.status == s));