I have class "Postavke" and then i store it into
List<Postavke> postavke = new List<Postavke>();
Now i want to find some elemnt (property) from this List. I know "Name", "Surname" and i want to get "Address".
How to get "Adress" if i know "Name" and "Surname". All this are properties in "Postavke" class
whole class
public class Postavke
{
#region Properties
public string Name { get; set; }
public string Surname { get; set; }
public string Address { get; set; }
#endregion
#region Methods
public Postavke(string name, string surname, string address, string oznakaLokacije, string oznakaZapore)
{
Name = ean;
Surname = surname;
Address = address;
}
#endregion
}
You can query postavke for all results that contain the name and surname and put the results into a list. Putting the results into a list I find makes things easier to validate and handle unforseen items as from the looks of it it is possible that duplicate items could appear.
if the results must have all data within the list item then:
List<Postavke> results = new List<Postavke>();
var query1 = from a in postavke
where a.Name == searchName
&& a.Surname == searchSurname
select a;
results.AddRange(query1);
this list will have all the results that contain the exact name and surname.
If you just want the address then you can use:
List<string> results = new List<string>();
var query1 = from a in postavke
where a.Name == searchName
&& a.Surname == searchSurname
select a.Address;
results.AddRange(query1);
this will produce a list of addresses. From here you can then validate the list if you want by doing such things as checking to see how many items in the list there are so you know how you want to handle it etc.
If you want to use just either the name or the surname then you can remove the line that asks for one or the other.
If you end up with duplicates but the results are the same then you can change the line
results.AddRange(query1);
to
results.AddRange(query1.Distinct());
by using the Distinct() method it will sort the query and remove duplicates so the list will not be in the same order as it would if you didn't use it.
If you only wanted one result then it's worth validating it by checking how many items are in the list by using
results.Count
you could if it equals 1 carry on, otherwise throw up a message or some other way you may want to handle it. Other pieces of validation that are good is to set values ToLower() and Trim() during the search as to avoid actually changing the original text.
So taking the last query as an example:
List<string> results = new List<string>();
var query1 = from a in postavke
where a.Name.ToLower().Trim() == searchName.ToLower().Trim()
&& a.Surname.ToLower().Trim() == searchSurname.ToLower().Trim()
select a.Address;
results.AddRange(query1);
you can also filter the query with the where clause after you make the query by doing:
List<string> results = new List<string>();
var query1 = from a in postavke
select a.Address;
query1 = query1.Where(h => h.Name == searchName);
query1 = query1.Where(h => h.Surname == searchSurname);
results.AddRange(query1);
The 2 where clauses were split to show you can perform where clause at different points so you could have where clauses within if statements. you can combine the 2 into:
query1 = query1.Where(h => h.Name == searchName && h.Surname == searchSurname);
Hopefully this helps
This will work if you can be sure there's exactly one match
var address = poatavke.Where(p=>p.Name == name && p.Surname == surname).Single().Address;
If you don't know if there's no matches or exactly one you can do:
var posta = poatavke.Where(p=>p.Name == name && p.Surname == surname).SingleOrDefault()
var address = posta == null ? string.Empty : posta.Address;
if you don't know how many matches there's going to be but always want the first (or are using ET which doesn't understand Single())
var posta = poatavke.Where(p=>p.Name == name && p.Surname == surname).FirstOrDefault()
var address = posta == null ? string.Empty : posta.Address;
Related
I'm running a query in my project with multiple joins. I want to provide the WHERE clause with a variable instead of hard coded as it is now but cannot seem to get the correct syntax.
var data = (from a in db.StudentData
join b in db.Contacts on a.SID equals b.SID
join c in db.Addresses on a.SID equals c.SID
join d in db.EntryQuals.DefaultIfEmpty() on a.SID equals d.SID
where a.SID == searchTxt
select new
{
ID = a.SID,
Birthdate = a.BIRTHDTE,
FirstName = a.FNAMES,
PreviousName = a.PREVSURNAME,
EntryQualAwardID = d.ENTRYQUALAWARDID,
AwardDate = d.AWARDDATE
}).ToList();
How can I get my WHERE clause to work with a variable (ie: a.[ fieldVar ] ) where fieldVar could be "SID" as it is in the code currently.
When dealing with user select-able search criteria you will need to code for the possible selections. When dealing with building searches I recommend using the Fluent syntax over the Linq QL syntax as it builds an expression that is easy to conditionally modify as you go. From there you can use a Predicate & PredicateBuilder to dynamically compose your WHERE condition.
Jacques solution will work, but the downside of this approach is that you are building a rather large & complex SQL statement which conditionally applies criteria. My preference is to conditionally add the WHERE clauses in the code to ensure the SQL is only as complex as it needs to be.
If you want to do something like a smart search (think Google with one text entry to search across several possible fields)
var whereClause = PredicateBuilder.False<StudentData>();
int id;
DateTime date;
if(int.TryParse(searchTxt, out id))
whereClause = whereClause.Or(x => x.SID == id);
else if(DateTime.TryParse(searchTxt, out date))
whereClause = whereClause.Or(x => x.BirthDate == date);
else
whereClause = whereClause.Or(x => x.FirstName.Contains(searchTxt));
var data = db.StudentData
.Where(whereClause)
.Select(a => new
{
ID = a.SID,
Birthdate = a.BIRTHDTE,
FirstName = a.FNAMES,
PreviousName = a.PREVSURNAME,
EntryQualAwardID = a.EntryQuals.ENTRYQUALAWARDID,
AwardDate = a.EntryQuals.AWARDDATE
}).ToList();
This does some basic evaluations of the search criteria to see if it fits the purpose of the search. I.e. if they can search by name, date, or ID and IDs are numeric, we only search on an ID if the criteria was numeric. If it looked like a date, we search by date, otherwise we search by name. (and potentially other searchable strings)
If they can search for ID, FirstName, and BirthDate and enter one or more of those as separate entry fields (Search criteria page) then based on which entries they fill in you can either pass separate nullable parameters and do the above based on what parameters are passed, or pass a list of search values with something like an Enum for which value was searched for:
I.e. by parameters:
private void ByParameters(int? id = null, DateTime? birthDate = null, string name = null)
{
var whereClause = PredicateBuilder.False<StudentData>();
if(id.HasValue)
whereClause = whereClause.Or(x => x.SID == id.Value);
if(date.HasValue)
{
DateTime dateValue = date.Value.Date;
whereClause = whereClause.Or(x => x.BirthDate == dateValue);
}
if (!string.IsNullOrEmpty(name))
whereClause = whereClause.Or(x => x.FirstName.Contains(name));
// ....
}
If the number of parameters starts to get big, then a custom type can be created to encapsulate the individual null-able values. I.e.:
[Serializable]
public class SearchCriteria
{
public int? Id { get; set; }
public DateTime? BirthDate { get; set; }
public string Name { get; set; }
}
private void ByParameters(SearchCriteria criteria)
{
// ....
}
Or you can compose a more dynamic parameter list object with a criteria type and value but it starts getting more complex than it's probably worth.
You can't really do that in Linq, sine linq needs to know the the type of the field at compile time. A workaround would be something like
where (fieldVar=="SID" && a.SID == searchTxt) ||
(fieldVar=="FNAMES" && a.FNAMES== searchTxt) || ...
This will also alert you at compile time if you are doing an illegal comparison, eg. comparing a date to a string.
var query = db.Customers
.Where("City == #0 and Orders.Count >= #1", "London", 10)
.OrderBy(someStringVariable)
.Select("new(CompanyName as Name, Phone)");
How can I check if someStringVariable is a valid order by expression before I run this query?
I want to check it instead of catching ParseException.
Valid string: "City ASC, Phone DESC"
Invalid string is not existing field or mistype in DESC: "City1 DESC1"
With help of Anu I am using this function but I would prefer some "TryParseQuery" in the Linq.Dynamic namespace.
public static bool IsValidOrderString(Type type, string ordering)
{
if (string.IsNullOrWhiteSpace(ordering)) return false;
var orderList = ordering.Trim().Split(',');
var fields = type.GetProperties().Select(property => property.Name).ToArray();
foreach (var orderItem in orderList)
{
var order = orderItem.TrimEnd();
if (order.EndsWith(" ASC", StringComparison.InvariantCultureIgnoreCase) || order.EndsWith(" DESC", StringComparison.InvariantCultureIgnoreCase)) order = order.Substring(0, order.Length - 4);
if (!fields.Contains(order.Trim())) return false;
}
return true;
}
as #mjwills pointed out, it is hard to do it with 100% reliability, but one thing you could do is compare 'someStringVariable' with list of columns in your table. You can find the list of columns via
.GetProperties().Select(property => property.Name).ToArray();
Again you need to be aware that this has many pitfalls. Properties can be mapped to column names that are not same as the property name.
I have a list of a model called results. I need to get those values from the results list which contain this particular string.
List<Search> results = new List<Search>();
results = db.Users.Select(f => new Search{ Name = f.Name, Type = f.OrganizationType.Name, County = f.County.Name }).ToList();
results = results.Where(w => (model.Name == null || w.Name.Contains(model.Name))).ToList();
While the first result query returns 5000 rows, the second one returns 0. What i am trying to do in the second query is if the Name is null or if the Name contains part of a string, add it to the results list.
Am I missing something?
I did check a couple of links which basically asked me to do the same like Check if a string within a list contains a specific string with Linq
I have checked the value for model.Name and it shows up properly. Also the query works if there is no search string that is when Model.Name = null, I get all the records
Consider this statement: Name is null or if the Name contains part of a string I hope you need to check an item in db.Users for null and Contains. One more thing I have to add here is- if x.Name is null then the following .Contains will raise NullReferanceException So you have to consider that as well. Now take a look into the following query:
List<Search> results = db.Users.Where(x=> x.Name==null || (x.Name !=null && x.Name.Contains(model.Name)))
.Select(f => new Search{ Name = f.Name, Type = f.OrganizationType.Name, County = f.County.Name }).ToList();
I have a List<T> of Customers that contains information like: Name, Product, Note, Booking Date, and UnreadMessage.
My goal is to filter customers using these fields and using AND operator but what's troubling me is when there is a field that is not used for filtering.
For example, an assistant will look for a customer name with a specific product. I could have a LINQ query that will look like this.
var a = Customers.Where(x => x.name.Contains("someone") && x.product.Contains("nike"));
Another example is, it will look for a customer with, with a specific product, with some note
var a = Customers.Where(x => x.name.Contains("someone") && x.product.Contains("nike") && x.note.Contains("some note"));
Another example, it will look for a product and booking date
var a = Customers.Where(x => x.product.Contains("someone") && x.bookingdate=DateTime.Now);
I hope you notice how many differenct queries I will write for this kind of filtering.
Name, product, note, booking date, or unread messages only
name and product
name and note
name and booking date
name and unread messages
product and note
product and booking date
etc etc etc etc
I am writing an Windows tablet application by the way so DataTable and LINQ Dyanmics are not possible where I can just write a string expression.
I am aksing for an advice and help how to solve this kind of filtering.
Why not combine Where?
var result = Customers
.Where(item => (null == name) || item.name.Contains(name))
.Where(item => (null == product) || item.product.Contains(product))
.Where(item => (null == note) || item.note.Contains(note))
...
So if you don't want to filter out by any parameter (name, product, etc.) just set it to null.
You can just build your statement dynamically. if this is linq to sql you will benefit from simpler execution plans with this approach:
public class test
{
public string name;
public string lastname;
}
class Program
{
static void Main(string[] args)
{
var list = new List<test>
{
new test{name = "john", lastname = "smith"}
};
string fname = "aa";
string lname = "sm";
var select = list.Select(c=>c);
if (fname != null)
select = select.Where(c => c.name.Contains(fname));
if (lname != null)
select = select.Where(c => c.lastname.Contains(lname));
var result = select.ToList();
}
}
I have got a bad requirement to do; anyway I have to implement that in my application.
I have a Track class
public class Track
{
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
and i have some test data
List<Track> Records = new List<Track>
{
new Track { City = "a", Name = "a", Country = "i" }, // Track 1
new Track { City = "b", Name = "b", Country = "i" }, // Track 2
new Track { City = "a", Name = null, Country = "J" }, // Track 3
new Track { City = "c", Name = "a", Country = "J" }, // Track 4
new Track { City = "b", Name = "a", Country = null}, // Track 5
};
Requirement is i should query the data from Records based on values passed. If any of the property is null then search criteria should ignore that property. It should query based on NonNull properties.
Example:
If i query for City = a, Name = "b", Country = "i" then Result is: Track 1 & Track 3
If i query for City = c, Name = "p", Country = "w" then Result is: Track 4
Name & Country have null values in Track 3 & Track 5.So it will ignore in search. Hope it is clear
I finally land up with below logic
var filterRecords = new List<Track>();
if (!Records.Any(t => string.IsNullOrWhiteSpace(t.City)))
{
filterRecords = Records.Where(c => c.City == _city).ToList(); // Here _city is the method parameter.. assume "a"
}
if (!Records.Any(t => string.IsNullOrWhiteSpace(t.Country)))
{
filterRecords = filterRecords.Where(c => c.City == _country).ToList(); // Here _country is the method parameter.. assume "c"
}
Track class has 12 properties. Checking for 12 times like above is not good sign.
I would like to achieve this by using LINQ or any other which is simple.
Any suggestions please?.
Best solution came to my mind is to build aggregate filter (You can use your Track object for that, because it already has all possible properties for filtering collection, and they are nullable):
Track filter = records.Aggregate(
new Track() { City = _city, Country = _country, Name = _name },
(f, t) => new Track()
{
City = String.IsNullOrEmpty(t.City) ? null : f.City,
Country = String.IsNullOrEmpty(t.Country) ? null : f.Country,
Name = String.IsNullOrEmpty(t.Name) ? null : f.Name
},
f => f);
This will require only one iteration over collection to define which fields has null. Then simply apply filter to your records:
var query = from t in Records
where (filter.City == null || t.City == filter.City) &&
(filter.Country == null || t.Country == filter.Country) &&
(filter.Name == null || t.Name == filter.Name)
select t;
You can easily chain these expressions together to create something like the following. Enumerating the records X times is going to slow down your code. Example:
var actualResult = Records
.Where(x => x.City == _city || string.IsNullOrEmpty(x.City))
.Where(x => x.Country == _country || string.IsNullOrEmpty(x.Country))
/// .... and so on
.ToList()
Now, if you're looking to not just write 12 lines of code, there are more complicated solutions that involve Reflection and mapping, but that's not really needed in this situation. If your property count is huge, then maybe it might be worth it. But 12 properties is small enough that there isn't much code smell here to me.
If I'm understanding, it should be this simple:
var results = Records.Select(p => p.City != null &&
p.Country != null &&
p.Name != null).ToList();
do the quality and quantity of results returned matter to you?
I assume you have mechanisms to handle the quantity.
You can validate your search keywords before throwing queries. Do you only care about nulls? How about redundant keywords?
I would consider:
1. validate keywords - 12 can be looped.
2. Build the search keyword strong
3. Shoot a query
Seems pretty straightforward, unless there's more to it than what you described here.
Please recorrect me, if my understanding of your question is not in the expected direction.
something like this
var listRecords = from track in Records
where (track.city == _city && !string.IsEmpyOrNull(track.city)) &&
(track.Name== _name && !string.IsEmpyOrNull(track.Name))
select track;
and you can add the rest of the conditions