CQLINQ for list of methods returning a specific type or interface? - ndepend

What is the CQLINQ to get list of methods returning a (compatible) specific type or interface?

You can get inspiration from such query:
let listOfT = ThirdParty.Types.WithFullName(
"System.Collections.Generic.IList<T>").Single()
let compatibleTypes = listOfT.TypesThatImplementMe.Concat(listOfT)
from m in Methods.Where(m => m.ReturnType != null && compatibleTypes.Contains(m.ReturnType))
select new { m, m.ReturnType }

Related

Query a list of list of objects in Dart?

I need to get all the details of a specific client:
I have a list of list for the details of all the clients:
List<List<ClienteDetails>> _listaClientDetails = List<List<ClienteDetails>> ();
I want to get the details for a specific client, and I'm trying to do it by using this code: I
var result = _listaProductosFactura.where((detailsList) => detailsList.where((cliente) => cliente.id == id)).toList();
But this code is wrong. "The return type 'Iterable' isn't a 'bool', as required by the closure's context."
Does someone know what would be the right code?
The problem with your code is that this part of it doesn't return a boolean value :
detailsList.where((cliente) => cliente.id == id)
it returns an iterable from your inner list which is not a boolean.
So the first "where" method cannot return an iterable as it doesn't have a boolean result
var result = _listaProductosFactura.where((detailsList) => //you must have a boolean result here not an iterable
//but detailsList.where((cliente) => cliente.id == id) gives you an iterable
You can do something like this to get the result you want:
List<List<ClienteDetails>> _listaClientDetails = List<List<ClienteDetails>> ();
var result;
for(List<ClienteDetails> clienteDetails in _listaClientDetails){
result = clienteDetails.where((cliente)=>cliente.id == id).toList();
//goes through the inner list and get the element where cliente.id == id
}

Entity Framework: check if object exists and check if it has an associated object

In a many-to-many relationship between File and Category I want to check if a file exists and if so, if it has any categories (because there's a chance it may not have any) :
public bool existsInDBAndHasCategories(string path)
{
using (WinFileContextContainer c = new WinFileContextContainer())
{
return c.File.Any((o => o.path == path));
}
}
This checks if a file with this path has a record in the database. I got this from a thread on this site. Truth be told I am still not good with LINQ and lambdas, so I don't know how to extend it to give me BOOLEAN for any categories as well. Thanks in advance for the time.
You just have to add another condition to your method (Assuming you have defined Categories as a list of Category in File class) :
return c.File.Any((o => o.path == path && o.Categories.Any()));
If you are not familiar with Lamba, start learning simple LinQ, before you move on to lambda inside Linq queries.
You code shoud be like this:
public bool existsInDBAndHasCategories(string path)
{
using (WinFileContextContainer c = new WinFileContextContainer())
{
var query = from f in c.File
where f.Path == path &&
(f.Categories != null || f.Categories.Count != 0)
select f;
return (f.Count != 0)
}
}

MongoDB - combining multiple Numeric Range queries (C# driver)

*Mongo Newbie here
I have a document containing several hundred numeric fields which I need to query in combination.
var collection = _myDB.GetCollection<MyDocument>("collection");
IMongoQuery mongoQuery; // = Query.GT("field", value1).LT(value2);
foreach (MyObject queryObj in Queries)
{
// I have several hundred fields such as Height, that are in queryObj
// how do I build a "boolean" query in C#
mongoQuery = Query.GTE("Height", Convert.ToInt16(queryObj.Height * lowerbound));
}
I have several hundred fields such as Height (e.g. Width, Area, Perimeter etc.), that are in queryObj how do I build a "boolean" query in C# that combines range queries for each field in conjunction.
I have tried to use the example Query.GT("field", value1).LT(value2);, however the compiler does not accept the LT(Value) construct. In any event I need to be able to build a complex boolean query by looping through each of the numeric field values.
Thanks for helping a newbie out.
EDIT 3:
Ok, it looks like you already have code in place to build the complicated query. In that case, you just needed to fix the compiler issue. Am assuming you want to do the following (x > 20 && x < 40) && (y > 30 && y < 50) ...
var collection = _myDB.GetCollection<MyDocument>("collection");
var queries = new List<IMongoQuery>();
foreach (MyObject queryObj in Queries)
{
//I have several hundred fields such as Height, that are in queryObj
//how do I build a "boolean" query in C#
var lowerBoundQuery = Query.GTE("Height", Convert.ToInt16(queryObj.Height * lowerbound));
var upperBoundQuery = Query.LTE("Height", Convert.ToInt16(queryObj.Height * upperbound));
var query = Query.And(lowerBoundQuery, upperBoundQuery);
queries.Add(query);
}
var finalQuery = Query.And(queries);
/*
if you want to instead do an OR,
var finalQuery = Query.Or(queries);
*/
Original Answer.
var list = _myDb.GetCollection<MyDoc>("CollectionName")
.AsQueryable<MyDoc>()
.Where(x =>
x.Height > 20 &&
x.Height < 40)
.ToList();
I have tried to use the example Query.GT("field", value1).LT(value2);,
however the compiler does not accept the LT(Value) construct.
You can query MongoDB using linq, if you are using the official C# driver. That ought to solve the compiler issue I think.
The more interesting question I have in mind is, how are you going to construct that complicated boolean query?
One option is to dynamically build an Expression and then pass that to the Where
My colleague is using the following code for something similar...
public static IQueryable<T> Where<T>(this IQueryable<T> query,
string column, object value, WhereOperation operation)
{
if (string.IsNullOrEmpty(column))
return query;
ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");
MemberExpression memberAccess = null;
foreach (var property in column.Split('.'))
memberAccess = MemberExpression.Property
(memberAccess ?? (parameter as Expression), property);
//change param value type
//necessary to getting bool from string
ConstantExpression filter = Expression.Constant
(
Convert.ChangeType(value, memberAccess.Type)
);
//switch operation
Expression condition = null;
LambdaExpression lambda = null;
switch (operation)
{
//equal ==
case WhereOperation.Equal:
condition = Expression.Equal(memberAccess, filter);
lambda = Expression.Lambda(condition, parameter);
break;
//not equal !=
case WhereOperation.NotEqual:
condition = Expression.NotEqual(memberAccess, filter);
lambda = Expression.Lambda(condition, parameter);
break;
//string.Contains()
case WhereOperation.Contains:
condition = Expression.Call(memberAccess,
typeof(string).GetMethod("Contains"),
Expression.Constant(value));
lambda = Expression.Lambda(condition, parameter);
break;
}
MethodCallExpression result = Expression.Call(
typeof(Queryable), "Where",
new[] { query.ElementType },
query.Expression,
lambda);
return query.Provider.CreateQuery<T>(result);
}
public enum WhereOperation
{
Equal,
NotEqual,
Contains
}
Currently it only supports == && !=, but it shouldn't be that difficult to implement >= or <= ...
You could get some hints from the Expression class: http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx
EDIT:
var props = ["Height", "Weight", "Age"];
var query = _myDb.GetCollection<MyDoc>("CName").AsQueryable<MyDoc>();
foreach (var prop in props)
{
query = query.Where(prop, GetLowerLimit(queryObj, prop), WhereOperation.Between, GetUpperLimit(queryObj, prop));
}
// the above query when iterated over, will result in a where clause that joins each individual `prop\condition` with an `AND`.
// The code above will not compile. The `Where` function I wrote doesnt accept 4 parameters. You will need to implement the logic for that yourself. Though it ought to be straight forward I think...
EDIT 2:
If you don't want to use linq, you can still use Mongo Query. You will just need to craft your queries using the Query.And() and Query.Or().
// I think this might be deprecated. Please refer the release notes for the C# driver version 1.5.0
Query.And(Query.GTE("Salary", new BsonDouble(20)), Query.LTE("Salary", new BsonDouble(40)), Query.GTE("Height", new BsonDouble(20)), Query.LTE("Height", new BsonDouble(40)))
// strongly typed version
new QueryBuilder<Employee>().And(Query<Employee>.GTE(x => x.Salary, 40), Query<Employee>.LTE(x => x.Salary, 60), Query<Employee>.GTE(x => x.HourlyRateToClients, 40), Query<Employee>.LTE(x => x.HourlyRateToClients, 60))

Getting the previous element of a IOrderedEnumeration

I have a enumeration of objects :
public IOrderedEnumerable<RentContract> Contracts {
get { return RentContracts.OrderByDescending(rc => rc.DateCreated); }
}
I have to compare a given RentContract instance with its previous RenContract instance on the list to highlight changes between the two objects, which is the most correct method to get the previous element ?
This is not possible directly. You can do it like this:
var input = new SomeClass[10]; //test data
var zipped = input.Zip(new SomeClass[1].Concat(input), (a, b) => { a, b });
var result = zipped.Where(x => x.b == null || x.a.DateCreated < x.b.DateCreated.AddHours(-1)); //some example
This solution is zipping the sequence with itself, but offset by one null element.

Entity Framework calling MAX on null on Records

When calling Max() on an IQueryable and there are zero records I get the following exception.
The cast to value type 'Int32' failed because the materialized value is null.
Either the result type's generic parameter or the query must use a nullable type.
var version = ctx.Entries
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.Max(e => e.Version);
Now I understand why this happens my question is how is the best way to do this if the table can be empty. The code below works and solves this problem, but its very ugly is there no MaxOrDefault() concept?
int? version = ctx.Entries
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.Select(e => (int?)e.Version)
.Max();
Yes, casting to Nullable of T is the recommended way to deal with the problem in LINQ to Entities queries. Having a MaxOrDefault() method that has the right signature sounds like an interesting idea, but you would simply need an additional version for each method that presents this issue, which wouldn't scale very well.
This is one of many mismatches between how things work in the CLR and how they actually work on a database server. The Max() method’s signature has been defined this way because the result type is expected to be exactly the same as the input type on the CLR. But on a database server the result can be null. For that reason, you need to cast the input (although depending on how you write your query it might be enough to cast the output) to a Nullable of T.
Here is a solution that looks slightly simpler than what you have above:
var version = ctx.Entries
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.Max(e =>(int?)e.Version);
Try this to create a default for your max.
int version = ctx.Entries
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.Max(e =>(int?)e.Version) ?? 0;
You could write a simple extension method like this, it returns the default value of type T if no records exist and is then apply Max to that or the query if records exist.
public static T MaxOrEmpty<T>(this IQueryable<T> query)
{
return query.DefaultIfEmpty().Max();
}
and you could use it like this
maxId = context.Competition.Select(x=>x.CompetitionId).MaxOrEmpty();
I couldnt take no for an answer :) I have tested the below and it works, I havent checked the SQL generated yet so be careful, I will update this once I have tested more.
var test = ctx.Entries
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.MaxOrDefault(x => x.Version);
public static TResult? MaxOrDefault<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
where TResult : struct
{
return source
.Select(selector)
.Cast<TResult?>()
.Max();
}
Try this:
IEnumerable<AlertsResultset> alerts = null;
alerts = (from POA in SDSEntities.Context.SDS_PRODUCT_ORDER_ALERT
join A in SDSEntities.Context.SDS_ALERT on POA.ALERT_ID equals A.ALERT_ID
orderby POA.DATE_ADDED descending
select new AlertsResultset
{
ID = POA.PRODUCT_ORDER_ALERT_ID == null ? 0:POA.PRODUCT_ORDER_ALERT_ID ,
ITEM_ID = POA.ORDER_ID.HasValue ? POA.ORDER_ID.Value : POA.PRODUCT_ID.Value,
Date = POA.DATE_ADDED.Value,
orderType = SDSEntities.Context.SDS_ORDER.Where(o => o.ORDER_ID == POA.ORDER_ID.Value).FirstOrDefault().ORDER_TYPE,
TransactionNumber = POA.PRODUCT_ID.HasValue ? (SDSEntities.Context.SDS_PRODUCT.Where(p => p.PRODUCT_ID == POA.PRODUCT_ID.Value).FirstOrDefault().TRANSACTION_NUMBER) : (SDSEntities.Context.SDS_ORDER.Where(o => o.ORDER_ID == POA.ORDER_ID.Value).FirstOrDefault().TRANSACTION_NUMBER),
Publisher = POA.PRODUCT_ID.HasValue ?
(
SDSEntities.Context.SDS_PRODUCT.Where(p => p.PRODUCT_ID == POA.PRODUCT_ID.Value).FirstOrDefault().PRODUCT_TYPE_NUMBER == "ISSUE" ? (from prod in SDSEntities.Context.SDS_PRODUCT
join ji in SDSEntities.Context.SDS_JOURNAL_ISSUE on prod.PRODUCT_ID equals ji.PRODUCT_ID
join j in SDSEntities.Context.SDS_JOURNAL on ji.JOURNAL_ID equals j.JOURNAL_ID
where prod.PRODUCT_ID == POA.PRODUCT_ID
select new { j.PUBLISHER_NAME }).FirstOrDefault().PUBLISHER_NAME : (from prod in SDSEntities.Context.SDS_PRODUCT
join bi in SDSEntities.Context.SDS_BOOK_INSTANCE on prod.PRODUCT_ID equals bi.PRODUCT_ID
join b in SDSEntities.Context.SDS_BOOK on bi.BOOK_ID equals b.BOOK_ID
where prod.PRODUCT_ID == POA.PRODUCT_ID
select new { b.PUBLISHER_NAME }).FirstOrDefault().PUBLISHER_NAME
)
: (SDSEntities.Context.SDS_ORDER.Where(o => o.ORDER_ID == POA.ORDER_ID.Value).FirstOrDefault().PUBLISHER_NAME),
Alert = A.ALERT_NAME,
AlertType = A.ALERT_TYPE,
IsFlagged = POA.IS_FLAGGED.Value,
Status = POA.ALERT_STATUS
});
how about
var version = ctx.Entries
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.Max(e => (int?)e.Version);
less ugly, more elegant
I want to suggest a merge from the existing answers:
#divega answer works great and the sql output is fine but because of 'don't repeat yourself'
an extension will be a better way like
#Code Uniquely showed. But this solution can output more complex sql as you needed.
But you can use the following extension to bring both together:
public static int MaxOrZero<TSource>(this IQueryable<TSource> source,
Expression<Func<TSource, int>> selector)
{
var converted = Expression.Convert(selector.Body, typeof(int?));
var typed = Expression.Lambda<Func<TSource, int?>>(converted, selector.Parameters);
return source.Max(typed) ?? 0;
}
You can use:
FromSqlRaw("Select ifnull(max(columnname),0) as Value from tableName");