I have the problem in where condition please check this
<Uni_Details Uni_ID="U001" User_Mode="New">
<Uni_Name>
<Full_Name>Asian</Full_Name>
<Short_Name />
</Uni_Name>
<Asc_Uni>
<Asc_Details Asc_Name="Stafford">
<Asc_Add>fsfadfsdfsdfsdf</Asc_Add>
<Asc_Tel>+44 34234234234</Asc_Tel>
<Asc_Country>United Kingdom</Asc_Country>
<Asc_Web>www.ac.lk</Asc_Web>
</Asc_Details>
</Asc_Uni>
<Branch>
<Branch_Details Branch_Name="Head Office">
<Branch_Add>dasdasdadsd</Branch_Add>
<Branch_City>Colombo</Branch_City>
<Branch_Country>Sri Lanka</Branch_Country>
<Branch_Tel>+94 342432423</Branch_Tel>
</Branch_Details>
<Branch_Details Branch_Name="Access Tower">
<Branch_Add>dfgdfgdfgdf</Branch_Add>
<Branch_City>Colombo</Branch_City>
<Branch_Country>Sri Lanka</Branch_Country>
<Branch_Tel>+94 342432453</Branch_Tel>
</Branch_Details>
</Branch>
<Uni_EMail>info#apiit.lk</Uni_EMail>
<Uni_Web>www.apiit.lk</Uni_Web>
<Course_Data>
<Course_Details Course_ID="U001C001">
<Course_Name>Computer Course</Course_Name>
<Course_Qual>Pass O/L</Course_Qual>
<Course_Dur>3 Months</Course_Dur>
<Course_Content>
<Course_Conent_List>C#.net</Course_Conent_List>
<Course_Conent_List>VB.Net</Course_Conent_List>
<Course_Conent_List>Design Practices</Course_Conent_List>
</Course_Content>
<Course_Fee>
<Fee_Amount Amount_Currency="SL Rs.">5000.00</Fee_Amount>
<Fee_Comment>Onwards</Fee_Comment>
</Course_Fee>
<Course_Desc>Learn Basic Programming practices</Course_Desc>
<Course_Next>Next October</Course_Next>
<Category_List>
<Cat_ID>2</Cat_ID>
<Cat_ID>1</Cat_ID>
</Category_List>
</Course_Details>
</Course_Data>
</Uni_Details>
<Uni_Details Uni_ID="U002" User_Mode="New">
<Uni_Name>
<Full_Name>American College</Full_Name>
<Short_Name>AC</Short_Name>
</Uni_Name>
<Asc_Uni>
<Asc_Details Asc_Name="American College USA">
<Asc_Add>fasdfsdfsdfsdsdfs</Asc_Add>
<Asc_Tel>+94 112 230623</Asc_Tel>
<Asc_Country>United States</Asc_Country>
<Asc_Web>www.ac.lk</Asc_Web>
</Asc_Details>
</Asc_Uni>
<Branch>
<Branch_Details Branch_Name="Head Office">
<Branch_Add>FFSDFASDFSDF</Branch_Add>
<Branch_City>Colombo</Branch_City>
<Branch_Country>Sri Lanka</Branch_Country>
<Branch_Tel>+94 112 230623</Branch_Tel>
</Branch_Details>
</Branch>
<Uni_EMail>info#ac.lk</Uni_EMail>
<Uni_Web>www.ac.lk</Uni_Web>
<Course_Data>
<Course_Details Course_ID="U002C0001">
<Course_Name>Computer Course</Course_Name>
<Course_Qual>O/L Pass</Course_Qual>
<Course_Dur>3 Months</Course_Dur>
<Course_Content>
<Course_Conent_List>C#.net</Course_Conent_List>
<Course_Conent_List>VB.Net</Course_Conent_List>
<Course_Conent_List>Design Practices</Course_Conent_List>
</Course_Content>
<Course_Fee>
<Fee_Amount Amount_Currency="SL Rs.">5000</Fee_Amount>
<Fee_Comment></Fee_Comment>
</Course_Fee>
<Course_Desc>Basics</Course_Desc>
<Course_Next>Next October</Course_Next>
<Category_List>
<Cat_ID>1</Cat_ID>
</Category_List>
</Course_Details>
<Course_Details Course_ID="U002C0002">
<Course_Name>Accounting Course</Course_Name>
<Course_Qual>O/L Pass</Course_Qual>
<Course_Dur>6 Months</Course_Dur>
<Course_Content>
<Course_Conent_List>Accounts Basics</Course_Conent_List>
<Course_Conent_List>Business Studies</Course_Conent_List>
<Course_Conent_List>Acc Pack</Course_Conent_List>
</Course_Content>
<Course_Fee>
<Fee_Amount Amount_Currency="SL Rs.">10000</Fee_Amount>
<Fee_Comment></Fee_Comment>
</Course_Fee>
<Course_Desc>Basic Accounting</Course_Desc>
<Course_Next>Next January</Course_Next>
<Category_List>
<Cat_ID>3</Cat_ID>
<Cat_ID>2</Cat_ID>
</Category_List>
</Course_Details>
</Course_Data>
</Uni_Details>
this is my XML file I need to retrieve all data which cat_id is 1
var data = (from cats in data_file.Elements("Uni_Data").Elements("Uni_Details")
where cats.Element("Course_Data").Element("Course_Details").Element("Category_List").Element("Cat_ID").Value == cat_id.ToString()
select new
{
uni_name = cats.Element("Uni_Name").Element("Full_Name").Value.ToString(),
uni_short = cats.Element("Uni_Name").Element("Short_Name").Value.ToString(),
price = cats.Element("Course_Data").Element("Course_Details").Element("Course_Fee").Element("Fee_Amount").Value.ToString()
});
however this works if I have cat_id 1 as my first element if its in second place it won't listed so plz help me with this
The problem is with the way the end of your where clause is setup: Element("Cat_ID").Value == cat_id.ToString().
Specifically, the Element("Cat_ID") part will check the first child "Cat_ID" element. So if Cat_ID 1 is the second item, it won't be found. Instead, you need to check all child elements for a match.
var data = (from cats in data_file.Elements("Uni_Data").Elements("Uni_Details")
let catId = cats.Element("Course_Data").Element("Course_Details").Element("Category_List").Elements("Cat_ID").FirstOrDefault(c => c.Value == cat_id.ToString())
where catId != null
select new
{
uni_name = cats.Element("Uni_Name").Element("Full_Name").Value.ToString(),
uni_short = cats.Element("Uni_Name").Element("Short_Name").Value.ToString(),
price = cats.Element("Course_Data").Element("Course_Details").Element("Course_Fee").Element("Fee_Amount").Value.ToString()
});
The query uses a let clause to store the result of the FirstOrDefault call, which uses the predicate to match the criteria. Next, if it isn't null then the rest of the query works as before. If it's null it means no match was found.
That said, your query has a lot of repeated elements. It also uses .Value.ToString() in a few places, which is redundant since the Value property already returns a string. I would clean up the query as follows:
var data = from cats in data_file.Elements("Uni_Data").Elements("Uni_Details")
let uniName = cats.Element("Uni_Name")
let details = cats.Element("Course_Data").Element("Course_Details")
let catId = details.Element("Category_List").Elements("Cat_ID").FirstOrDefault(c => c.Value == cat_id.ToString())
where catId != null
select new
{
uni_name = uniName.Element("Full_Name").Value,
uni_short = uniName.Element("Short_Name").Value,
price = details.Element("Course_Fee").Element("Fee_Amount").Value
};
Related
I use System.Linq.Dynamic to query entities with dynamic 'where' expressions. I'm querying object that has property "newValue" of string type. Exemplary value would be : "{\"ProcessId\":764, \"ProcessLength\":1000}".
I can't use == because I want to find all hits where the property contains "ProcessId:764", regardless on the rest of the string. The thing is, that stored string contains escape sign "\" and double quotes and I can't figure out what it should like exactly..
dbContext.Processes.Where("#newValue.Contains(\"ProcessId\":764\")") brings error, however dbContext.Processes.Where("#newValue.Contains(\":764\")") works correctly. I guess it must be something with backslashes or double quotes in my query but can't figure it out on my own..
There are two things to note here:
If you know at compile time the column that should be queried (i.e., newValue), just use standard Linq: var list = items.Where(i => i.NewValue.Contains("904")).ToList().
If you do want to use dyanmic Linq, What you'd usually want is to apply Where on some column, e.g. Where("SomeColumn.Contains("something")"), or Where("SomeColumn.Contains(#0)", new string[] {"something"}).
So, in your case, this should work: items.Where("newValue.Contains(\"904\")").
Doing Where("#newValue.Contains("something")") doesn't really make sense, since #newValue would be parsed as a string literal. See also this comment on a similiar question.
Here' a quick example:
public static void Main(string[] args)
{
var items = new []
{
new { Id = "1", Title = "ProcessId: 123"},
new { Id = "4", Title = "ProcessId: 456"},
new { Id = "7", Title = "ProcessId: 789"},
}.ToList();
// returns null, because the string "Title" doesn't contain the string "7"
var res1 = items.Where("#0.Contains(\"7\")", new string[] {"Title"}).FirstOrDefault();
// works - returns the 3rd element of the array
var res2a = items.Where("Title.Contains(#0)", new string[] {"ProcessId: 789"}).FirstOrDefault();
var res2b = items.Where("Title.Contains(\"ProcessId: 789\")").FirstOrDefault();
}
#HeyJude Thanks for the effort, but I still can't get it to work. It has somehow gone wronger and now I can't even fetch correct rows giving only ProcessId number..
Let me give you more detailed description of my setup. In the database there's a table with column "NewValue", I use this column to store json string of current (for the time of creating row in the table) representation of some object e.g. object Process. So the column stores for example string of {"ProcessId":904,"ProcessLength":1000}. To fetch this data from db I create collection of table's records: var items = (from l in db.JDE_Logs
join u in db.JDE_Users on l.UserId equals u.UserId
join t in db.JDE_Tenants on l.TenantId equals t.TenantId
where l.TenantId == tenants.FirstOrDefault().TenantId && l.Timestamp >= dFrom && l.Timestamp <= dTo
orderby l.Timestamp descending
select new //ExtLog
{
LogId = l.LogId,
TimeStamp = l.Timestamp,
TenantId = t.TenantId,
TenantName = t.TenantName,
UserId = l.UserId,
UserName = u.Name + " " + u.Surname,
Description = l.Description,
OldValue = l.OldValue,
NewValue = l.NewValue
});. Then I query it to find matching rows for given ProcessId number e.g. query = "#NewValue.Contains(\"904,)\")";
items = items.Where(query);
This should fetch back all records where NewValue column contains the query string, but this doesn't work. It compiles and 'works' but no data are fetched or fetched are only those records where 904 appears later in the string. Sounds stupid but this is what it is.
What should the query string look like to fetch all records containing "ProcessId":904?
I try to multiply 2 values from different table but it's keep error like this:
Here's my code:
//Label12 is in datalist
var Label12 = (Label)(((Button)sender).Parent).FindControl("Label12");
var item2 = from c in db.OrderTemps
join o in db.Products
on c.Prod_ID equals o.Prod_ID
select new
{
o.Prod_ID,
o.Prod_Price, //Type "Decimal"
c.Amount, //Type "Integer"
c.Total, //Type "Decimal
s = o.Prod_Price * c.Amount
};
foreach (var i in item2)
{
Label12.Text = Convert.ToString(i.s); //an error happen here!!
}
Any help appreciated.
There is nothing wrong with you LINQ query. If no records joined, then there will be nothing to enumerate and you will skip foreach body. I think you have Label12 equal to null. Check if it really exist on senders parent.
SIDE NOTE: Why are you trying to assign text in loop? Label will keep only last value assigned.
Check whether your amount value in OrderTemps table is null. or Check whether you really have a controller which has the ID = Label12.
Nothing wrong in your Linq query...
I'm using C#, EF5, and Lambda style queries against SQL.
I have the usual scenario of binding data to gridviews. Some of the results for my columns may be too long (character count) and so I only want to display the first 'n' characters. Let's say 10 characters for this example. When I truncate a result, I'd like to indicate this by appending "...". So, let's say the following last names are returned:
Mercer, Smith, Garcia-Jones
I'd like them to be returned like this:
Mercer, Smith, Garcia-Jon...
I was doing something like this:
using (var context = new iaiEntityConnection())
{
var query = context.applications.Where(c => c.id == applicationPrimaryKey);
var results = query.ToList();
foreach (var row in results)
{
if (row.employerName.Length > 10)
{
row.employerName = row.employerName.Substring(0, Math.Min(10, row.employerName.ToString().Length)) + "...";
}
if (row.jobTitle.Length > 10)
{
row.jobTitle = row.jobTitle.Substring(0, Math.Min(10, row.jobTitle.ToString().Length)) + "...";
}
}
gdvWorkHistory.DataSource = results;
gdvWorkHistory.DataBind();
However, if I change my query to select specific columns like this:
var query2 = context.applications.Select(c => new
{
c.id,
c.applicationCode,
c.applicationCategoryLong,
c.applicationType,
c.renew_certification.PGI_nameLast,
c.renew_certification.PGI_nameFirst,
c.renew_certification.PAI_homeCity,
c.renew_certification.PAI_homeState,
c.reviewStatusUser,
c.dateTimeSubmittedByUser
})
The result appears to become read-only if specific columns are selected, and I really should be selecting just the columns I need. I'm losing my ability to edit the result set.
So, I'm rethinking the entire approach. There must be away to select the first 'n' characters on select, right? Is there anyway to append the "..." if the length is > 10 on select? That seems trickier. Also, I guess I could parse through the gridview after bind and make this adjustment. Or, perhaps there is a way to maintain my ability to edit the result set when selecting specific columns?
I welcome your thoughts. Thanks!
To quote MSDN
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.
So you would have to define a class and select into that if you want read write capability.
e.g.
public class MyClass {
public int id { get; set; }
public string applicationCode {get; set; }
// rest of property defintions.
}
var query2 = context.applications.Select(c => new MyClass {
id = c.id,
applicationCode = c.applicationCode,
// Rest of assignments
};
As to just providing 10 character limit with ... appended. I'm going to assume you mean on the applicationcategoryLog field but you can use the same logic on other fields.
var query2 = context.applications.Select(c => new
{
c.id,
c.applicationCode,
applicationCategoryLong = (c.applicationCategoryLong ?? string.Empty).Length <= 10 ?
c.applicationCategoryLong :
c.applicationCategoryLong.Substring(0,10) + "...",
c.applicationType,
c.renew_certification.PGI_nameLast,
c.renew_certification.PGI_nameFirst,
c.renew_certification.PAI_homeCity,
c.renew_certification.PAI_homeState,
c.reviewStatusUser,
c.dateTimeSubmittedByUser
})
I have set of records in a database table lets call it Components Table which is defined as follows.
The administrator can disable some of the components using disableflag which is the last column of the table. If a particular component is disabled it should not appear in the gridview of the user.
I'm getting the data from the database and presenting through the gridview as shown here, if you observe the SNo values are not in order.
The linq query that i'm using to retrieve the data is:
var gridViewResults = from results in db.Components where results.DisableFlag == false
select new { SNo = results.SNo, ComponentNames = results.Component_Name, Size = results.Size__in_MB_, Price = results.Price__in_SEK_, TotalDownloads = results.Total_Downloads, Description = results.Description };
But I want the data to be shown in order meaning with SNo to be 1, 2, 3, 4 with out dependency on the database table SNO values: for reference look at this.
I'm not able to figure out how to use the linq query to achieve this:
I have tried this query:
(db.Components.AsEnumerable().Select((iterator)=> new{iterator.SNo + 1})
But i think it is absurd. Can some one help me out on this.
Thanks in anticipation.
If you're absoutely certain you want to ignore the database numbers (why output the numbers if they don't actually correspond to anything?) you may be able to try the following:
var gridViewData = from results in db.Components
where results.DisableFlag == false
select new
{
ComponentNames = results.Component_Name,
Size = results.Size__in_MB_,
Price = results.Price__in_SEK_,
TotalDownloads = results.Total_Downloads,
Description = results.Description
};
var gridViewResults = gridViewData.AsEnumerable().Select((item, index) => new
{
SNo = index + 1,
ComponentNames = item.ComponentNames,
Size = item.Size,
Price = item.Price,
TotalDownloads = item.TotalDownloads,
Description = item.Description
});
EDIT: Alternate solution from How To Project a Line Number Into Linq Query Results
EDIT2: Fix for unsupported select by SQL: Linq error - "NotSupportedException: Unsupported overload used for query operator 'Select'"
Hi everyone here is the final answer. Joshua did all of the work. A big thanks to him. Just want to highlight the answer to anyone with the same problem for the future. If any one want to vote up please vote for Joshua
var gridViewData = from results in db.Components
where results.DisableFlag == false
select new
{
ComponentNames = results.Component_Name,
Size = results.Size__in_MB_,
Price = results.Price__in_SEK_,
TotalDownloads = results.Total_Downloads,
Description = results.Description
};
var gridViewResults = gridViewData.AsEnumerable().Select((item, index) => new
{
SNo = index + 1,
ComponentNames = item.ComponentNames,
Size = item.Size,
Price = item.Price,
TotalDownloads = item.TotalDownloads,
Description = item.Description
}).ToList();
This should work.
I have a requirement to extract a distinct subset of rows from a DataTable, and thought LINQ2DataSets may be a useful and clean way to do this, however it appears that it is not possible to simply identify return rows from a LINQ2DS query as follows
var result = from r in fips.AsEnumerable() select
r.Field<string>("FACILITY_PROCESS_SUB_GROUP_CODE"),
r.Field<string>("PROCESS_SUB_GROUP_NAME"),
r.Field<string>("...
as I start getting errors after the first comma.
Is this a correct assumption, and how would I get around it to return a subset of columns from the dataset that I can apply a Distinct() method to?
You forgot the new statement and field names:
var result = from r
in fips.AsEnumerable()
select new
{
FacProcess = r.Field<string>("FACILITY_PROCESS_SUB_GROUP_CODE"),
GroupName = r.Field<string>("PROCESS_SUB_GROUP_NAME"),
Item3 = r.Field<string>("Item3")
};
You can also explicitly declare that you are going to use a type:
var result = from r
in fips.AsEnumerable()
select new MyType("InitClassParams")
{
FacProcess = r.Field<string>("FACILITY_PROCESS_SUB_GROUP_CODE"),
GroupName = r.Field<string>("PROCESS_SUB_GROUP_NAME"),
Item3 = r.Field<string>("Item3")
};
Scott Guthrie (VP Developer Devision, Microsoft) has some good info about LINQ (he talks about LINQ to SQL, but most of it applies regardless).
Then apply the distinct clause:
var result = from r
in fips.AsEnumerable()
select new
{
FacProcess = r.Field<string>("FACILITY_PROCESS_SUB_GROUP_CODE"),
GroupName = r.Field<string>("PROCESS_SUB_GROUP_NAME"),
Item3 = r.Field<string>("Item3")
}
distinct;
Then put it to a list or iterate over it. Nothing will be selected/distincted/etc until something like on of the following is run:
var list = result.ToList()
foreach(var item in result) {}