where clause in linq list - asp.net

H, I have a list of orders and I'm trying to filter this list. So far I have:
Dim orders = _orderController.LoadAll().ToList()
which does indeed give me a list of orders which I can display on a gridview.
How could I filter this list to say: where order.referencenumber = "abc123"
and only give me one order in the list to display in the gridview
Cheers,

Try this:
VB:
Dim orders = _orderController.LoadAll().Where(Function(c) c.referencenumber = "abc").ToList();
C#:
var orders = _orderController.All().Where(o => o.referencenumber = "abc123").ToList();

You should apply the Where clause before your call to ToList
Dim orders = _orderController.LoadAll().Where(Function(c) c.referencenumber = "abc").ToList()
you should check you the examples found in the documentaion

Related

Getting LINQ query result into a list?

I'm converting old code to use LINQ. The old code looked like this:
// Get Courses
sqlQuery = #"SELECT Comment.Comment, Status.StatusId, Comment.DiscussionBoardId, DiscussionBoard.CourseId, Comment.CommentID
FROM Status INNER JOIN Comment ON Status.StatusId = Comment.StatusId INNER JOIN
DiscussionBoard ON Comment.DiscussionBoardId = DiscussionBoard.DiscussionBoardId
WHERE (DiscussionBoard.CourseID = 'CourseID')";
var comments = new List<Comment>(dataContext.ExecuteQuery<Comment>(sqlQuery));
I've converted the above SQL to LINQ:
var db = new CMSDataContext();
var query = from c in db.Comments
join s in db.Status on c.StatusId equals s.StatusId
join d in db.DiscussionBoards on c.DiscussionBoardId equals d.DiscussionBoardId
where d.CourseId == "CourseID"
select new
{
d.ItemType,
c.Comment1,
s.Status1,
c.DiscussionBoardId,
d.CourseId,
c.CommentID
};
The problem I've having, though, is with trying to get the results of the query into the List. Can someone offer me some pointers?
Thanks!
Try adding the ToList() method at the end of the query.
Enclose the whole query in parentheses and add .ToList() at the end.
Or add another line:
var list = query.ToList();
How about the ToList method: query.ToList() ?
You'll need to do two things.
First, change your select to create a new instance of Comment instead of an anonymous type.
Second, either wrap the whole query in a call to ToList() or store the results in a temporary variable and call ToList() on that variable to get the List<Comment> as a result.
Either (A) wrap the entire call with Enumerable.ToList(<your query>), (B) surround the entire query with parentheses and call the ToList extension method at the end, or (C) call query.ToList() as a separate statement.

how to group a query in linq to Entity

I am using linq to Entity to retrieve data from to different tables by joining them, but I also want to group them by the field problemDesc in order to get rid of unnecessary duplicate entries for the same problem.
here is the code:
using (AssistantEntities context = new AssistantEntities())
{
var problems = context.tblProblems;
var customers = context.tblCustomers;
var query =
from problem in problems
join customer in customers
on problem.CustID equals customer.custID
where problem.IsActive == true
orderby customer.isMonthlyService == true descending
select new
{
problemID = problem.problemID,
ProblemCreateDate = problem.ProblemCreateDate,
CustID = problem.CustID,
name = customer.name,
isMonthlyService = customer.isMonthlyService,
StationName = problem.StationName,
problemDesc = problem.problemDesc,
LogMeIn = problem.LogMeIn
};
return query.ToList();
}
I am doing query.toList() in order to use that list in a gridview as a dataSource.
and if it possible, also add a field that count the duplicate problems.
You have plenty of examples in the following link.
LINQ - Grouping Operators

ASP.Net LINQ to SQL group by syntax for System.Generic.IEnumerable Collection

.Net application calls Stored Procedure and returns collection which is stored as 'result.' I want to be able to group the results by 'CreatorLineOfBusinessID'. It returns that field along with several other fields. I would like to use a LINQ query on the 'result' data set. Thanks in advance.
Dim result As IEnumerable(Of eRefer_Reports.uspReport_ReferralsSentBetweenLinesOfBusinessResult)
strFromLOBID = " "
Session("FromLineOfBusiness") = strFromLOBID
strToLOBID = " "
Session("ToLineOfBusiness") = strToLOBID
result = repository.GetQueryResults(CDate(Me.txtStartDate.Text), CDate(Me.txtEndDate.Text), strFromLOBID, strToLOBID)
BindGridView(result)
Have you done any research on Linq grouping? Try the 101 examples here: http://msdn.microsoft.com/en-us/vstudio/bb688088
Dim orderGroups = From p In results Group p By Key = p.CreatorLineOfBusinessID Into Group _
Select CreatorBusinessId = Key, Referrals = Group
Then just iterate over orderGroups using the Key and the property Referrals which will be an IEnumerable<eRefer_Reports.uspReport_ReferralsSentBetweenLinesOfBusinessResult>
For Each lobBusiness in orderGroups
' Get the lobBusinessId : .CreatorBusinessId
' Get the IEnumerable results: .Referrals
Next
Dim query = result.GroupBy(Function(x) x.ID).ToList()
Should group the results the way you want.

Format XML data to display on a gridview

I am trying to format XML data to display on a grid.
Page1.aspx. This inserts XML data stored a xmldatatype:
WorkHistory workhis = js.Deserialize<WorkHistory>(json);
XmlDocument work = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "root");
objBLL.insert_XMLWork(work, Convert.ToInt64(ui.id));
Page2.aspx retrieves it and display on a grid:
DataTable FBWorkDt = objBLL.get_FacebookWork(FacebookUserId);
GrdWork.DataSource = FBWorkDt;
GrdWorkPub.DataBind();
get_FacebookWork(select workinfo from Fprofiles where Userid = FacebookUserId)
returns a DataTable
It displays in this format exactly.
WorkInfo
<root><work><employer><id>208571635850052</id><name>Netizen Apps</name></employer></work><id>1076483621</id></root>
How do I make a normal display instead of XML format?
Thanks
Sun
It depends a good deal on the shape of the DataTable you're returning, but assuming you want the display to be something like this:
`ID Name
-------------------- ---------------------
208571635850052 Netizen Apps`
You could use LINQ:
DataTable FBWorkDt = objBLL.get_FacebookWork(FacebookUserId);
var query = from x in FBWorkDt.AsEnumerable()
select new {
id = x.ID,
name = x.Name
};
GrdWork.DataSource = query.ToList();
GrdWorkPub.DataBind();
I haven't tried the code out, so there may be minor syntatic changes, but essentially what it's doing is:
Use LINQ to get a collection of a new anonymous type that has one entry per row with the id and name from the table. You have to use AsEnumerable() [contained in System.Data.DataSetExtensions].
Convert the LINQ result set to a List via .ToList() and bind it to the GridView.
If you can post a little more information - what exactly you mean by display, and the expected shape of the returned DataTable (i.e., what the columns in each row are) we can give you a better answer.
UPDATE
If you're storing the XML document above in your datastore and that is being returned in the table, try this code:
DataTable FBWorkDt = objBLL.get_FacebookWork(FacebookUserId);
XDocument xDoc = XDocument.Load(FBWorkDt.Rows[0][0].ToString());
var query = from x in xDoc.Descendants("employer")
select new
{
id = (string)x.Element("id"),
name = (string)x.Element("name")
}
GrdWork.DataSource = query.ToList();
GrdWorkPub.DataBind();
Same basic principal as above, except this time your querying over an XDocument instead of a DataTable.

perform "not in" query using linq from 2 datatables

i have a datatable which contains "InvalidCodes".
Before uploading the data to database(data is still in datatable), i want to perform linq on the datatable to remove Invalid entries and move them in another datatable
datatable allEntries ( entries yet to be uploaded in database)
datatable InvalidCodes(single column datatable - retrieved from database)
datatable invalidEntries
right now "allEnties" contains valid entries and invalid entries. the linq query on "allEntries" should move the nonexistend code entries to invalidEntries datatable.
plz help me perform this.
below is the query i formed but its not valid
string query = "select [CityCode] from [StateCity] ";
DataTable citylist = getDataTableFromSelect(query);
var result = from myrow in inputDt.AsEnumerable()
where !myrow.Field<string>("CityCode").Contains(from myrow2 in citylist.AsEnumerable() select myrow2.Field<string>("CityCode") )
select myrow;
I'd make a HashSet for the invalid city codes - this will allow the code to quickly/efficiently identify which of the codes are in the invalid set.
e.g. something like:
var invalidCityCodes = from myrow2 in citylist.AsEnumerable()
select myrow2.Field<string>("CityCode");
var invalidCityCodeHashSet = new HashSet<string>(invalideCityCodes);
var result = from myrow in inputDt.AsEnumerable()
where !invalidCityCodeHashSet.Contains(myrow.Field<string>("CityCode"))
select myrow;
You can also take both the results in 2 Different Lists and then you can
use
List1 = List1.RemoveAll(Item=>List2.Contains(Item))
This works fine with me and will work for you also.

Resources