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();
Related
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));
My table contains several columns and I need to select distinct rows in two specific columns using Linq.
My SQL equivalent is:
Select distinct Level1Id, Level1Name
from levels
What I currently do is:
db.levels.GroupBy(c=> c.Level1Id).Select(s => s.First())
This will retrieve the whole row not only Level1Id and Level1Name. How can I specify the columns I want to retrieve in this linq query?
With Select, you can specify the columns in an anonymous object and then use Distinct on that:
db.levels.Select(l => new{ l.Level1Id, l.Level1Name }).Distinct();
try
db.levels.Select(c => new {c.Level1Id, c.Level1Name}).Distinct();
Specify the two columns in your LINQ query select, create an anonymous object with Level1Id and Level1Name properties:
var query = (from v in db.levels
select new { Level1Id = v.Level1Id, Level1Name = v.Level1Name }).Distinct();
and use each item like this:
foreach (var r in query){
int valId = r.LevelId;
int level = r.Level1Name;
//do something
}
You are so close, one more step:
var result = db.levels.GroupBy(c=> new { c.Level1Id, c.Level1Name })
.Select(s => s.First())
The key thing is: Anonymous type uses structural comparison, that's why GroupBy or any other answer do work.
I'm querying a datatable using linq, I then query the results to filter out what I want, the problem is that I need to query it for each value of an array these values are like this ,2, or ,22, or ,21, etc
so I usually do this
results = from a in results
where a.countryId.ToString().Contains(value)
select a;
what I would like to do is this
foreach(string str in arrayval)
{
results += from a in results
where a.countryId.ToString().Contains(str)
}
can anyone help or give me some clues
thanks
Looks like you want to select results based on comparison from the array values. Something like. Select * from table where ID in (1,2,3). Instead of concatenating results you can try the following query.
var result = from a in result
where arrayval.Contains(a.CountryId.ToString())
select a;
if your arrayval is an int type array then you may remove .ToString() at the end of a.CountryID
Try this
results.Where(a=> arrayval.Contains(a.CountryId.ToString()).Aggregate("", (a,b)=> a+b);
I would create a list of your array values e.g.
List<string> list = new List<string>()
{
"2",
"12",
"20",
//etc...
};
and then do
var result = results.Where(p => list.Contains(p.countryId.ToString()));
Basically you are only select countryId's that are contained in the list.
Suppose I have a collection of strings.
How do I select all the elements that don't contain a certain parameter value?
List<string> TheList = .....
var TheCleanList = (from s in TheList
where s != parameter
select s).ToList();
I was thinking about where s!= parameter but I'm wondering if there's a cleaner way to do it.
Thanks.
If you don't need a new list you don't need Linq for this - use Remove()- this avoids having to create a new list:
If you want to remove all strings that are equal to Parameter:
TheList.RemoveAll(s => s == Parameter);
If you want to remove all strings that contain Parameter (not clear from your question):
TheList.RemoveAll(s => s.Contains(Parameter));
You mean:
List<string> TheList = .....
var TheCleanList = (from s in TheList
where !s.Contains(parameter)
select s).ToList();
You can use String.Contains
var TheCleanList = (from s in TheList
where !s.Contains(parameter)
select s).ToList();
Or
var TheCleanList = TheList.Where(s => !s.Contains(parameter)).ToList();
String.Contains is case-sensitive. If you want a case-insensitve:
string lower = parameter.ToLower();
...
where s.ToLower().Contains(lower)
I'm trying to work with the .NET AJAX autocompletion extension. The extension is expecting the following...
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
My database queries are in a LINQ var object. I'm getting compile-time errors about not being able to convert type IQueryable to string[].
InventoryDataContext assets = new InventoryDataContext();
var assetsInStorage = from a in assets.Assets
where a.Name.Contains(prefixText)
orderby a.Name ascending
select new[] { a.Manufacturer.Name, a.Name };
return (string[])assetsInStorage;
In order to get an string[] at first you must select only one string property on your query, not an anonymous object:
var assetsInStorage = from a in assets.Assets
where a.Name.Contains(prefixText)
orderby a.Name ascending
select a.Manufacturer.Name; // or a.Name
assetsInStorage at this moment is an IEnumerable<string>, and then you should convert it to string[] by:
return assetsInStorage.ToArray();
Your assetsInStorage doesn't appear to be an IEnumerable<string>... as such, you'd have to project your anonymous type into a string.
assetsInStorage.Select(a=>a[0] + a[1])
(Or however you want to convert that anonymouns type to a string.)
And then you can return .ToArray():
return assetsInStorage.Select(a=>a[0]+a[1]).ToArray();
If you want a single array that contains both a.Manufacturer.Name and a.Name for each of the assets, you can do that with a slight modification of CMS's answer:
var assetsInStorage = from a in assets.Assets
where a.Name.Contains(prefixText)
orderby a.Name ascending
select new[] { a.Manufacturer.Name, a.Name };
At this point, assetsInStorage is an IEnumerable<string[]> which also counts as an IEnumerable<IEnumerable<string>>. We can flatten this down to a single IEnumerable<string> using SelectMany and then turn it into an array.
return assetsInStorage.SelectMany(a => a).ToArray();
In this way, you're not required to select only a single string value.
This should do the trick:
InventoryDataContext assets = new InventoryDataContext();
var assetsInStorage = from a in assets.Assets
where a.Name.Contains(prefixText)
orderby a.Name ascending
select String.Concat(x.ManufacturerName, " ", x.Name);
return assetsInStorage.ToArray();
EDITED based on comment... EF is able to interpret String.Concat(), so the additional enumeration wasn't necessary.
Try:
return assetsInStorage.ToArray();