Linq query how to select all columns - c#

I have a linq query which is giving me desired output :
var data = (from c in dtskip.AsEnumerable()
select new[] {
c.Field<string>("Suburb"), c.Field<string>("Postcode"), c.Field<string>("State"),c.Field<string>("ID"), c.Field<string>("SEARCHKEY"), c.Field<string>("RATING"), c.Field<string>("DELIVERY")
});
How can i select all the column instead of giving name like c.field<string>("postcode") .My output is the data only from datatable dtskip :
output:
["DARWIN","0800","NT","2","DARWINNT","A","Delivery Area"]
,["ALAWA","0810","NT","5","ALAWANT","A","Delivery Area"],
["BRINKIN","0810","NT","6","BRINKINNT","A","Delivery Area"],
is there any other way i can get the output in dis way from datatable using linq query .

DataRow contains an ItemArray member which returns all the data in that row as an array, the downside is they are all returned as objects but if all your columns are the same type you can cast the ItemArray in line to the desired type (in this case string)
dtskip.Rows.Cast<DataRow>().Select(r => r.ItemArray.Cast<string>());
This will give you an IEnumerable<IEnumerable<string>> to work with.

have you tried
var data = (From c in dtskip
select c).AsEnumerable(); //Not sure about the AsEnumerable :s

Are you looking for something like this?
var data = dtskip.AsEnumerable().
Select(x => new
{
Suburb = x.Field<string>("Suburb"),
Postcode= x.Field<string>("Postcode"),
State= x.Field<string>("State"),
Id= x.Field<string>("ID"),
Searchkey = x.Field<string>("SEARCHKEY"),
Rating = x.Field<string>("RATING"),
Delivery = x.Field<string>("DELIVERY")
});

Related

How can get values using LINQ from multilevel variable

I want to unable to fetch values using LINQ. I am using below code for fetching data.
SearchParameters sp3 = new SearchParameters()
{
Filter = "name eq 'test'",
Top = 5,
QueryType = QueryType.Full,
Select= new List<string>() { "Query" },
};
if (highlights)
{
sp3.HighlightPreTag = "<b>";
sp3.HighlightPostTag = "</b>";
}
DocumentSearchResult suggestResult = _indexClient1.Documents.Search(term,sp3);
List<string> suggestions = (from p in suggestResult
.Results.Select(s => s.Document)
.Select(y => y.Values.ToString())
select p).ToList();
Hierarchy is Document->Result->Query.
I am getting values till Result level but I want to get data till Query Level.
I am not expert in LINQ.
screenshot
output
I think what you are looking for is something like this:
suggestResult.Results.SelectMany(s => s.Document.Select(d => d.Query)).ToList()
It should give you a list of all Query-Objects over all Document Results.
If you want the Query as string you have to get another property of Query in the inner Select or call ToString() on it.

What is the best way to write a two column query in LINQ to Entity 6? And save the results to two different variables?

How would you write "SELECT col.a, col.b FROM TABLE WHERE ID = 1" in LINQ to Entity 6 so that you could save col.a into variable A and col.b into variable B. You can do this with SqlReader by retrieving the index or column name, but with LINQ to Entity it is returned as one object. When returning a two field LINQ query to a list, both field are saved to the first index of the list and can only be accessed as the same list element. Is it standard to create two LINQ queries, one for each variable? Or am I missing part of the process?
Current query:
var result = (from col in cxt.Table
where col.ID == "1"
select new {col.a, col.b}).ToList();
If you are expecting exactly one record to return from database then what you can do:
var result = cxt.Table.FirstOrDefault(x => x.ID == "1");
//Notice that might be null if has not result
var a = result.a;
var b = result.b;
Will look very similar in query syntax but I think this method syntax neater in this case
I am not sure what exactly you are looking for. But selecting two variable by Linq is not so hard.
var value = (from ta in db.YourTable
where ta.ID = id
select new {
A = ta.a,
B = ta.b
}).FirstOrDefault();
var a = value.A;
var b = value.B;
If you use ToList() instead of FirstOrDefault(), you will get a list contain zero or more objects. You can simply use a loop to get field from each object.
forach(var value in values)
{
var a = value.A;
var b = value.B;
}

Linq Distinct not bringing back the correct results

I'm trying to select a distinct values from a DataTable using Linq. The DataTable gets populated from an excel sheet which has dynamic column apart from each excel sheet has a column name SERIAL NUMBER which is mandatory.
I have a DataTable for demo purpose which consist of 4 serial number as:
12345
12345
98765
98765
When I do
var distinctList = dt.AsEnumerable().Select(a => a).Distinct().ToList();
If I do
var distinctList = dt.AsEnumerable().Select(a => a.Field<string>("SERIAL NUMBER").Distinct().ToList();
Then I get the correct results, however but it only contains the one column from dt and not all the other columns
I get all four records instead of 2. Can someone tell me where I'm going wrong please.
The problem is that Distinct method by default uses the default equality comparer, which for DataRow is comparing by reference. To get the desired result, you can use the Distinct overload that allows you to pass IEqualityComparer<T>, and pass DataRowComparer.Default:
The DataRowComparer<TRow> class is used to compare the values of the DataRow objects and does not compare the object references.
var distinctList = dt.AsEnumerable().Distinct(DataRowComparer.Default).ToList();
For more info, see Comparing DataRows (LINQ to DataSet).
So, you want to group them by Serial Number and retrieve the full DataRow? Assuming that after grouping them we want to retrieve the first item:
var distinctList = dt.AsEnumerable().GroupBy(a => a.Field<string>("SERIAL NUMBER"))
.Select(a => a.FirstOrDefault()).Distinct().ToList();
EDIT: As requested
var distinctValues = dt.AsEnumerable().Select(a => a.Field<string>("SERIAL NUMBER")).Distinct().ToList();
var duplicateValues = dt.AsEnumerable().GroupBy(a => a.Field<string>("SERIAL NUMBER")).SelectMany(a => a.Skip(1)).Distinct().ToList();
var duplicatesRemoved = dt.AsEnumerable().Except(duplicateValues);
In ToTable method the first parameter specifies if you want Distinct records, the second specify by which column name we will make distinct.
DataTable returnVals = dt.DefaultView.ToTable(true, "ColumnNameOnWhichYouWantDistinctRecords");
Here there is no need to use linq for this task !
Using Linq a GroupBy would be better suited, by the sounds of it.
var groups = dt.AsEnumerable().GroupBy(a => a.SerialNumber).Select(_ => new {Key = _.Key, Items = _});
This will then contain groupings based on the Serial Number. With each group of items having the same serial number, but other property values different.
Try this:
List<string> distinctValues = (from row in dt.AsEnumerable() select row.Field<string>("SERIAL NUMBER")).Distinct().ToList();
However to me this also works:
List<string> distinctValues = dt.AsEnumerable().Select(row => row.Field<string>("SERIAL NUMBER")).Distinct().ToList();

How to convert to int and then compare in linq query c#

IEnumerable<classB> list = getItems();
//dt is datatable
list = list.Where(x => Convert.ToInt32( !dt.Columns["Id"]) == (x.Id));
I want to only keep the items in the list which match in datatable id column. The rest are removed. I m not doing it right.
The datatable can have: ID - 1,3,4,5,7
The list can have: ID - 1,2,3,4,5,6,7,8,9,10
I want the output list to have: ID - 1,3,4,5,7
Your code won't work because you're comparing a definition of a column to an integer value. That's not a sensible comparison to make.
What you can do is put all of the values from the data table into a collection that can be effectively searched and then get all of the items in the list that are also in that collection:
var ids = new HashSet<int>(dt.AsEnumerable()
.Select(row => row.Field<int>("Id"));
list = list.Where(x => ids.Contains(x.Id));
Try this one
var idList = dt.AsEnumerable().Select(d => (int) d["Id"]).ToList();
list = list.Where(x => idList.Contains(x.Id));
You can't do it like that. Your dt.Columns["Id"] returns the DataColumn and not the value inside that column in a specific datarow. You need to make a join between two linq query, the first one you already have, the other you need to get from the DataTable.
var queryDt = (from dtRow in dt
where !dtRow.IsNull("Id")
select int.Parse(dtRow["Id"])).ToList();
Now the join
var qry = from nonNull in queryDt
join existing in list on nonNull equals list.id

How to select specific column in LINQ?

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.

Categories

Resources