I have a LINQ query where I want to select and read the p.Api value.
var api = DataAccessNew.Instance.dcServers.Where(p => p.Ip == IpAddress).Select(p => p.Api);
How do I read the p.Api value?
I have tried api.ToString() but I get SQL instead of actual column value.
You are getting an IEnumerable<> back (and your ToString call is showing you the value of that expression).
If you are expecting a single value, do this:
var api = DataAccessNew.Instance.dcServers
.Where(p => p.Ip == IpAddress)
.Select(p => p.Api)
.Single();
You might be interested to read about the other methods like Single(): SingleOrDefault, First, FirstOrDefault. Which one you used depends on whether you are expecting a single or multiple values returned (Single vs. First) and what you want to happen if there are no values (the *Default methods will return the type default instead of throwing an exception).
Or if you want to look at all the returned values:
var api = DataAccessNew.Instance.dcServers
.Where(p => p.Ip == IpAddress)
.Select(p => p.Api);
foreach (var apiValue in api)
{
// apiValue will have the value you're looking for.
}
Try this snippet of code:
string apiValue = api.FirstOrDefault().ToString();
your syntex seems ok..
By the way try this
string api =DataAccessNew.Instance.dcServers.Where(p => p.Ip == IpAddress).Select(p => p.Api).FirstOrDefault();
if p.Ip is a unique key in your table you could try to add .FirstOrDefault() after your Linq query.
public string getselectedvalue(ListBox l)
{
string vtext="",vval="";
var selectedQueryText = l.Items.Cast<ListItem>().Where(item => item.Selected);
var selectedQueryVal = l.Items.Cast<ListItem>().Where(item => item.Selected).Select(item => item.Value);
vtext= String.Join("','", selectedQueryText ).TrimEnd();
vval= String.Join("','", selectedQueryVal ).TrimEnd();
return v;
}
Related
I want to get the distinct list of studentname from the database who are still active. Ihis is what I've tried.
string strJSON = JsonConvert.SerializeObject(
context.Students.Where(x => x.IsActive == 1).Distinct().ToList());
Distinct function works on all columns, so I assume that you want only student name.
string strJSON = JsonConvert.SerializeObject(
context
.Students
.Where(x => x.IsActive==1)
.Select(x=>x.StudentName)
.Distinct()
.ToList()
);
am a newbie in linq.. am stuck with one scenario. ie,
i have to sort the search results based on user input.
user inputs are Last Name, First Name and Title. for input 3 drop downs are there and i have to sort result based on the values selected.
i tried
order = Request["orders"].Split(',');
var param = order[0];
var p1 = typeof(Test).GetProperty(param);
param = order[1];
var p2 = typeof(Test).GetProperty(param);
param = order[2];
var p3 = typeof(Test).GetProperty(param);
model.Test = (from tests in model.Test
select tests).
OrderBy(x => p1.GetValue(x, null)).
ThenBy(x => p2.GetValue(x, null)).
ThenBy(x => p3.GetValue(x, null));
but it doesn't works.
i want qry like this
from tests in model.Test
select tests).OrderBy(x => x.lastname).
ThenBy(x => x.firstname).ThenBy(x => x.Title);
order[0]== lastname but how can i use it in the place of OrderBy(x => x.order[0])..?
Thanks in advance.
i solved my case as follows
// list of columns to be used for sorting
List<string>order = Request["orders"].Split(',').ToList();
//map the column string to property
var mapp = new Dictionary<string, Func<Test, string>>
{
{"FirstName", x => x.FirstName},
{"LastName", x => x.LastName},
{"SimpleTitle", x => x.SimpleTitle}
};
//user inputted order
var paras = new List<Func<Test, string>>();
foreach (var para in order)
{
if(!string.IsNullOrEmpty(para))
paras.Add(mapp[para]);
}
//sorting
model.Test= model.Test.OrderBy(paras[0]).ThenBy(paras[1]).ThenBy(paras[2]);
Thanks all,
Actually you are looking for dynamic linq query than you can try out Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)
which allow to do like this
it means you can dynamically pass string propertyname to short you collection in orderby function
You can also read about : Dynamic query with Linq
You can compose the expression (any Expression) manually from pieces and then append it to the previous part of query. You can find more info, with example in "Sorting in IQueryable using string as column name".
I have a listbox that I am trying to populate with the result of a SQL Server query via a Entity Framework linq/lambda query. I am feeding the query with a value from a combobox. I keep getting lot of errors like the following: Unable to create a constant value of type 'System.Object'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
Any suggestions on how to fix this? I just want two fields to populate in a grid
var pAt = ent.Patterns.Where(p => p.Case_Id == (cbCase.SelectedItem as Case).Case_Id).Select(x => new Pattern{ PatternID = x.PatternID, Pattern1 = x.Pattern1 });
listBox1.DataSource = pAt;
listBox1.ValueMember = "PatternID";
listBox1.DisplayMember = "Pattern1";
Try this instead :
var pAt = ent.Patterns.AsEnumerable()
.Where(p => p.Case_Id == ((Case)cbCase.SelectedItem).Case_Id)
.Select(x => new Pattern{ PatternID = x.PatternID, Pattern1 = x.Pattern1 });
Hope this will fix your issue.
Separate the code parts from the SQL parts. Entity Framework can't necessarily construct an SQL query using code objects, but you can usually work around it. Eg:
var caseId = (cbCase.SelectedItem as Case).Case_Id;
var pAt = ent.Patterns.Where(p => p.Case_Id == caseId)
.ToArray()
.Select(x => new Pattern { PatternID = x.PatternID, Pattern1 = x.Pattern1 });
I would like to select only the records that have the field "1" from the string eventTriggers (that looks something like this : "00100010" )
I've tried and succesfully done so with more than 1 calls .. but i doubt its efficient. Basically I would want something like this ... but apprently LINQ does not support this.
(LINQ to Entities does not recognize the method 'Char get_Chars(Int32)' method, and this method cannot be translated into a store expression.)
using (var service = new dB.Business.Service.BaseBusinessService<memo>())
{
List<memo> result = service.Repository.GetQuery().Where(p => p.ID == ID && p.eventTriggers[index] == '1').ToList();
}
Any hints towards the correct solution ? Thank you !
I Had the same problem and solved It with substring.
ervice.Repository.GetQuery().Where(p => p.ID == ID && p.eventTriggers.Substring(index,1) == "1").ToList();
EF can't convert the char array operation into a valid query. How about
IEnumerable<Memo> memos
using (var service = new dB.Business.Service.BaseBusinessService<Memo>())
{
memos = service.Repository.GetQuery()
.Where(p => p.ID == ID).AsEnumerable();
}
var result = memos.Where(m => m.eventTriggers[index] == '1').ToList();
This gets all the memos with a matching ID locally then filters on the eventTriggers array.
Alternatively you could convert eventTriggers into a numeric value and use a bit mask, this would probably be a much faster query.
Linq looking like this,
using (var service = new dB.Business.Service.BaseBusinessService<Memo>())
{
result = service.Repository.GetQuery()
.Where(p =>
p.ID == ID
&&
m.eventTriggers & mask != 0).ToList();
}
more exapmles here
Solved:
using (var service = new dB.Business.Service.BaseBusinessService<memo>())
{
List<memo> result = service.Repository.GetQuery().Where(p => p.ID == ID && p.eventTriggers.Contains('1')).ToList();
}
I've an object list where each object contains an internal object list and what I would fetching is the father list (left list), however I'm forced to use SelectMany function..Is it possibile?
Naive Example:
var query = objList.SelectMany(p => p.InternalList)
.Where(internalObj => internalObj.SomeProprerty == true)
.SELECT(objList);
Is there any way to accomplish this?
Assuming you don't actually want objList, but instead the element of objList which we're looking at at the time, I think you just want:
var query = objList.SelectMany(p => p.InternalList, (o, p) => new { o, p })
.Where(pair => pair.p.SomeProperty)
.Select(pair => pair.o);
If that's not what you're after, it would really help if you'd give a concrete example.
EDIT: If you only want any example from objList where any element of the internal list has a SomeProperty value of true, you can do that more easily like this:
var value = objList.FirstOrDefault(o => o.InternalList.Any(p => p.SomeProperty));
if (value != null)
{
...
}