Is there a good way of requesting only specified columns from the database using LINQ? I want to be able to select only certain columns depending on arbitrary conditions from code.
You can create anonymous types for each condition, which contain only the columns you specify.
var anonymousType = from item in itemCollection
select new {Column1 = item.Column1, Column2 = item.Column2};
var anonymousType2 = from item in itemCollection
select new {Column2 = item.Column2, Column3 = item.Column3};
Not sure exactly what you mean.
Are you maybe wanting to pull different columns based on a conditional?
Something like this?
if(condition)
{
table.Select(x => x.ColumnA);
}
else
{
table.Select(x => x.ColumnB);
}
Related
I want to group by a datatable by the columns which are present in a List. Moreover I want to sum a column using group by result.
How to create a dynamic linq query for this?
In case you want to use a dynamic linq query for this, you can use System.Linq.Dynamic.Core.
The code could look like:
var result = context.Posts.GroupBy("BlogId").Select("new(Key, Sum(NumberOfReads) AS TotalReads)");
See also
https://dynamic-linq.net/basic-query-operators#groupby-by-a-single-key-and-do-a-sum
Just group by the identifier you need and then sum the column as below.
var lstYourClass = lstYourClass .GroupBy(x => x.Id).Select(z => new YourClassType
{
Amount= z.Sum(a => a.Amount),
}).ToList();
Hope it helps :)
I am using Linq to Sql and I need to fetch only the needed fields. This is something that I was able to accomplish using Dynamic Linq. Does anyone know how I can fetch only one or more fields and then add it to my Grid without re query and regenerate the whole object again?? Something similar to Merge method of a dataset but with Linq to SQL?
I hope I understand your question. Does one of these help you?
var List1 = db.myTable.Select(k => new myObject
{
ID = k.Id,
field1 = k.field1
});
var List2 = from k in db.myTable select new myObject()
{
ID = k.Id,
field1 = k.field1
};
else can you provide an example?
I am having at hierarchical table with the structure
ID, Name, FK_ID, Sortkey
Fetching the data in LINQ to SQL is straight forward:
var list = from ls in db.myTable
where ls.FK_ID == levelId
orderby ls.sortkey ascending
select ls;
And I can traverse down the tree by linking to the next levelId.
But what I can't figure out, if there is a way in LINQ, to check if there is any children
I could probably build a view, that added a flag to each record, but I would rather do this in LINQ, if possible.
What would even be the best practice for adding such a flag in SQL?
My idea on checking each record, is not the most performance friendly solution.
If you have set up the foreign key correctly, should you not have the 1 to Many mapping properties?
i.e. You could write
var listWithChildren = list.Where(l => l.Children.Any());
or going the other direction
var listWithParent = list.Where(l => l.FK_ID != null);
or using the query expression instead of fluent
var listWithChildren = from item in list
where item.Children.Any()
select item;
as you asked in your comments for a boolean flag, you could do
var updatedList = from item in list
select new
{
Item = item,
HasChildren = item.Children.Any()
};
I have to select specific column from my DataTable using linq
I am using this code
ds.Table[0].AsEnumerable().Where<DataRow>(r=>r.Field<int>("productID")==23).CopyToDataTable();
~
But it is giving me all columns and I need only PRODUCTNAME , DESCRIPTION , PRICE
How I can write this query?
To expand a bit on #lazyberezovsky, you can use an anonymous type projection to get all of the fields you want:
ds.Table[0].AsEnumerable()
.Where<DataRow>(r => r.Field<int>("productID") == 23)
.Select(r => new { ProductName = r.Field<string>("productName"),
Description = r.Field<string>("description"),
Price = r.Field<decimal>("price") });
I don't know what name and type your product name, description, and price fields are, so you will have to substitute those.
Use Select method:
ds.Table[0].AsEnumerable()
.Where<DataRow>(r=>r.Field<int>("productID")==23)
.Select(r => r.Field<int>("productID"));
UPDATE: In case you need to select several columns, you can return anonymous type:
var query = from row in dt.ds.Table[0].AsEnumerable()
where row.Field<int>("productID")==23
select new {
ProductID = x.Field<string>("productID"),
Foo = x.Field<string>("foo")
};
If you need to copy that data to new table, you'll face problem (CopyToDataTable requires collection of DataRow objects). See How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow to solve this problem.
I have three tables I'm getting info from: User, Field, FieldUserInput. I already know the userId which is what I use to find out what fields the user has input. Then I want to get the value of those fields that the user has input in FieldUserInput.
I first wrote this query in plain old sql but I want to use LINQ as much as possible since that's why I use Entity Framework.
SELECT fielduserinput.field_idField, fielduserinput.userInput, fielduserinput.time
FROM fielduserinput
WHERE fielduserinput.userId = #userId
Any suggestions as to how I would write this in LINQ?
Considering you have a datasource filled with data.
var matchingRows = from rows in fielduserinput.AsEnumarable()
where string.compare(rows["userId"].ToString(),userID)==0
select rows;
var result = from row in fielduserinput
where row.userId = "???"
select new { row.field_idField, row.userInput, ...};
var response = fielduserinput
.Where(x=>x.userid == #userid)
.Select(x=>new { field_idfieldid = x.field_idfieldid, etc })
.ToList()