LINQ Comparing Entities' Property to String Array - c#

I am using MVC and I have my entity model class which has a string property "type". My get method returns an array of strings to the post called objTypes[] from a MultiSelectList.
What I would like to do is a LINQ query to my db to query back only the objs that have type equal to one of the strings in the array. Similar to this:
objs = objs.Where(o => o.type == ("any of objType elements"))

You can use the Contains() method. Simply use:
var filteredObjs = objs.Where(o => objTypes.Contains(o.type));)

I think you can try this..
var objTypes = db.OBjs.select(a=>a.type).ToList();
var result = objs.Where(o => objTypes.Contains(o.type));

Related

dynamic property name in linq

I'm trying to write a linq query that takes a dynamic property name. So for example, if the property name is 'test', a simple query would look like this:
var test = testList.Select(x => x.test).Distinct().ToList();
But I want to dynamically generate the property name, eg:
var propertyName = "test";
var test = testList.Select(x => x.propertyName).Distinct().ToList();
I get an error because 'propertyName' isn't an actual property.
What would be the best way to achieve this?
You'd have to use reflection to do what you're trying to do:
var test = testList
.Select(x => x.GetType().GetProperty(propertyName).GetValue(x))
.Distinct()
.ToList();

Convert linq query to Generic string array

I know that I can cast my linq query to an array or list but this doesn't seem to help.
Here is my query:
var bracct = from DataRow x in _checkMasterFileNew.Rows
select new {BranchAccount = string.Format("{0}{1}", x["Branch"], x["AccountNumber"])};
When I attempt to convert it to a list or array:
List<string> tstx = bracct.ToList();
or this:
string[] stx = bracct.ToArray();
If give me this:
I am assuming I need to change my query but I'm not sure the best way to hanlde it. How do I get it to a generic collection of strings?
It won't work because you've created an anonymous type with 1 property which is a string. Instead, If all you want is to convert it into a List<string> do:
var bracct = (from DataRow x in _checkMasterFileNew.Rows
select string.Format("{0}{1}", x["Branch"], x["AccountNumber"])).ToList();
And if using c# 6.0 you can use string interpolation:
var bracct = (from DataRow x in _checkMasterFileNew.Rows
select $"{x["Branch"]}{x["AccountNumber"]}").ToList();
Your query is creating an anonymous type with a single member BranchAccount. If you actually just want a string, then just select that instead:
var bracct =
from DataRow x in _checkMasterFileNew.Rows
select string.Format("{0}{1}", x["Branch"], x["AccountNumber"]);
And now your ToList() call will return List<string>:
List<string> tstx = bracct.ToList();
You must select the property you are assigning the string to before performing ToList(), or remove the anonymous type and select string.Format() directly
Try this:
List<string> tstx = bracct.Select( x => x.BranchAccount ).ToList();

Is there a Linq equivalent for creating collection from subset of an object used in a previous collection

Is there a Linq equivalent for the following piece of code where Properties is a list of properties in the object T and entry is an instance of T.
I find that I do code like this ever so often and I Was wondering if there was a more simple clear way to do this using linq.
List<Object> args = new List<Object>();
for (int i = 0; i < Properties.Count; i++)
args.Add(typeof(T).GetProperty(Properties[i]).GetValue(entry));
Properties.Select(t => typeof(T).GetProperty(t).GetValue(entry)).ToList();
now if you use often, just create an extension method (in a static helper class)
public static IList<object> GetValuesFor<T>(this IEnumerable<string> properties, T instance) {
return properties.Select(t => typeof(T).GetProperty(t).GetValue(instance)).ToList();
}
and usage
var args = Properties.GetValuesFor(entry);
You are transforming properties into values, which means that you can use the Select method:
var args = Properies.Select( p => typeof(T).GetProperty(p).GetValue(entry) );
var args = Properties
.Select(x=> typeof(T).GetProperty(x).GetValue(entry))
.ToList();
This should be the equivalent, using the Select method:
var args = Properties
.Select(p => typeof(T).GetProperty(p))
.Select(p => p.GetValue(entry))
.ToList();
You can of course have the whole typeof(T).GetProperty(p).GetValue(entry) part in one Select - I've split it for clarity. Note that it doesn't make much difference in terms of memory/performance - it won't create any additional collection in between, because LINQ is lazily evaluated, and it won't "run" until the ToList call.

Contains statement in the LINQ queries

I want do something like this:
string test = alarmType;
db.Alarms.Where(alarmType.Contains(m => m.Type)).ToList();
But this doesn't work. How can I make such query? Is it the only way to use pure SQL?
UPD
I'm trying to find whether records is substring of the "test", not conversly.
You have to reverse the condition:
var query = db.Alarms
.Where(a => alarmType.Contains(a.Type))
.ToList();
However, your code sample is confusing, if alarmType is a string i don't know what you're trying to achieve.
string test = alarmType;
Update: if you're using LINQ-To-Sql and you want to find all records where the Type is a substring of alarmType you can use:
var query = db.Alarms
.Where(a => SqlMethods.Like(alarmType, string.Format("%{0}%", a.Type)))
.ToList();
Try the following
string test = alarmType;
var result = db.Alarms.Where(m => alarmType.Contains(m.Type)).ToList();
Your LINQ query isn't well-formatted. You have:
db.Alarms.Where(alarmType.Contains(m => m.Type)).ToList();
So the parameter you've passed to Contains is a lambda, which isn't what Contains takes,
Likeiwse, Contains returns a bool, so you've passed a bool to Where, which is also not a parameter type it takes.
What you want is to pass a lambda to Where, like so:
db.Alarms.Where(m => alarmType.Contains(m.Type)).ToList();
Note how now both the Where and the Contains are being passed parameters of the correct type.

WHERE clause using LINQ

The below code will select all the rows in a table, but I want to only select the id of the row that I pass into the method. I've tried it multiple ways and now starting fresh to see if I can get it work. Any help is appreciated.
Here's my code:
[WebMethod]
public static string getProjectByID(int id)
{
using (dbPSREntities4 myEntities = new dbPSREntities4())
{
var thisProject = myEntities.tbProjects.ToList();
JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(thisProject);
return json;
}
}
You'll want to use the Where method to filter the data:
var thisProject = myEntities.tbProjects.Where(x => x.yourIdColumn == id).ToList();
The where clause is fairly simple here. You just need to use a lambda expression to specify the condition you're matching on. If you're not familiar with them more info can be found here http://msdn.microsoft.com/en-us/library/bb397687.aspx the basics are you have a variable name followed by => on the right hand side you can do what you want with the variable and I find it easiest to think of it as working like a foreach where the variable name you declare is the iteration variable (an item in the list).
var thisProject = myEntities.tbProjects.Where(x => x.Id == id).ToList();

Categories