Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to get the vehicle type according to vehicle number. I need to select specific column from a list according to another column.
Here is my code:
protected void ddVehicleNo_SelectedIndexChanged(object sender, EventArgs e)
{
List<Exp_VehicleDTO> odata = (List<Exp_VehicleDTO>)Session["VehicleDTO"];
var vehityeps=odata.Select(x=>x.VehicleNo.Contains(x.VehicleType.Equals(Convert.ToInt32(ddVehicleNo.SelectedValue))))
}
This code causes error "the best overload method match for "string.contains(string)" has some invalid arguments".
Exp_vehicleDTO class
public class Exp_VehicleDTO
{
public int CompanyId { get; set; }
public int VehicleId { get; set; }
public int VehicleType { get; set; }
public string VehicleNo { get; set; }
public int Status { get; set; }
public DateTime CreatedDateTime { get; set; }
public string CreatedBy { get; set; }
public string CreatedMachine { get; set; }
}
You can get the vehicle type like so:
int vehicleType = odata.Single(x => x.VehicleNo.Equals(ddVehicleNo.SelectedValue)).VehicleType;
Single will take the first item that matches the condition. Note that it will throw an exception if the item isn't found, or if there are multiple matching items.
If you want to handle the case that the item isn't found, you can do something like this:
var vehicle = odata.SingleOrDefault(x => x.VehicleNo.Equals(ddVehicleNo.SelectedValue));
if (vehicle != null)
{
var vehicleType = vehicle.VehicleType;
}
else
{
// set combobox's SelectedIndex to -1
}
Difficult to help without knowing what error you are receiving but try changing your code to this:
protected void ddVehicleNo_SelectedIndexChanged(object sender, EventArgs e)
{
List<Exp_VehicleDTO> odata = (List<Exp_VehicleDTO>)Session["VehicleDTO"];
var vehityeps = odata
.Where(v => v.VehicleNo.ToString() == ddVehicleNo.SelectedValue)
.Select(v => v.VehicleType);
}
That should populate vehityeps with all VehicleType's where VehicleNo equals what the user has selected in the ddVehicleNo drop down.
UPDATED
I'm not sure what types are used Exp_VehicleDTO but my guess is VehicleNo is an int. To be safe with my solution this compares the values as strings.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to write a simple Console App, where I have a User class that looks like this:
class User
{
public string Name { get; set; }
public int Age { get; set; }
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
My goals is to get an input from the user for every property, but I want to check whether the user input
meets specific criterias. For example: when to user tries to enter a value for the Name property, I want to check whether or not the entered value starts with an uppercase letter, contains digits, is less than fifty characters, etc. and if the entered value is not valid, then I throw an exception and ask the user to try again, if it is valid, then we move onto the next property and so on.
My problem is that I can not figure out how to simplify this process, because what happens if I have a property that has to meet a hundred criterias.
Is there a simple way to check if the user input meets a lot of criteria and if not, I throw an exception, show a random error message and after that the user can try again.
One very simple way would be to create a dictionary of ValidationCriterias and corresponding Error Messages for any given class. Since its user input validation checks, I would just throw a valid friendly error message, instead of exception, since such errors were already anticipated.
The following code runs all the validation criterias, even though if any single fails and at the end outputs all the error messages in a pipe separated string.
If at least a single criteria fails , the function will return false.
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
public class ValidateProps<T> where T: class
{
public static bool RunRules(Dictionary<Expression<Func<T, bool>>, string> lst,
T myObj,
out string errorMessages)
{
errorMessages = "";
bool isSuccess = true;
foreach (var l in lst)
{
if (l.Key.Compile()(myObj) == false) isSuccess = false;
errorMessages += l.Key.Compile()(myObj) == true ? "" : "|" +l.Value;
}
errorMessages = errorMessages.Trim('|');
return isSuccess;
}
}
// Example Usage
User u = new User() { Name = "dd23dd", Age = 100 };
Dictionary<Expression<Func<User, bool>>, string> dict1 =
new Dictionary<Expression<Func<User, bool>>, string>()
{ {x => Char.IsUpper(x.Name.ToCharArray().ElementAt(0)), "Error Message 1" },
{x => !(x.Name.Any(char.IsDigit)), "Error Message 2"},
};
string errorMsgs = "";
bool n1 = ValidateProps<User>.RunRules(dict1, u, out errorMsgs);
My application is basically just a survey with questions and multiple choice answers. Questions have Answers, but a specific Answer may lead to a specific Question being asked which might otherwise not be asked at all. e.g. "Do you like chocolate?" (if yes ask...) "Do you prefer German or Dutch chocolate?"
In the Answer class, I am trying to populate a list property "DependentQuestions" which is meant to contain id numbers for the Quesiton(s) that will be asked next if this Answer is chosen. The problem is, I am always getting nothing and I'm not sure why. I confirmed the Answer.id is zero at the time the constructor runs by populating DependentQuestions with the commented code you'll see below.
Each Question has an icollection of Answers.
Question class:
public class Question
{
[Key]
public int id { get; set; }
public string question { get; set; }
public int? DependentAnswer { get; set; }
public virtual ICollection<Answer> answers { get; set; }
}
Answer class:
public class Answer
{
[Key]
public int id { get; set; }
public string answer { get; set; }
[Required]
public int questionId { get; set; }
public List<int> DependentQuestions { get; set; }
public Answer()
{
DependentQuestions = new List<int>();
using (dbSurvey db = new dbSurvey())
{
var _list = db.Questions.Where(q => q.DependentAnswer == id).Select(q => q.id).ToList();
if (_list.Any())
{
DependentQuestions.AddRange(_list);
}
//else
//{
// DependentQuestions.Add(id);
//}
}
}
}
The "answers" collection of the Question class is being filled with the Answers to the given Question and that works just fine, but the DependentQuestions list in the Answer class is always coming up empty since Answer.id is always zero at that point. So why is Answer.id always 0, and what can I do about it?
Constructor code is run before any property values are set, so at the point of executing the constructor all properties just contain their default values. That is why it is always 0.
I am not sure what are you using as a data access framework, but generally you can do few things:
Create Answer entity with id, so you always have it in constructor:
public Answer(int id)
If that's not an option, you could also have a lazy property loading questions as needed:
class Answer
{
private List<int> _dependentQuestions;
public List<int> DependentQuestions
{
get
{
if (_dependentQuestions == null)
// load questions here
return _dependentQuestions;
}
}
}
Note that this assumes id is already set, you probably should validate that too.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
my task is to group the data from a list of Subscription object which has the following structure:
public class Subscription
{
public string ApplicationId { get; private set; }
public string UserCode { get; private set; }
public string SubscriptionId { get; private set; }
public string SubscriptionCode { get; private set; }
public DateTime? StartDate { get; private set; }
public DateTime? EndDate { get; private set; }
}
The code return a list of subscription, so List. In my case I've several items with same ApplicationId but different StartDate and EndDate. Basically I have to group these items
in order to create a json structure like this:
"applicationId" : {
"subscriptions" : [
{
"startdate" : ...,
"enddate" : ...,
},
{
"startdate" : ...,
"enddate" : ...,
},
]
}
Can I achieve this using LINQ?
Try this:
subscriptions.GroupBy(item => item.SubscriptionCode)
.Select(group => new { Subscription = group.Key, Items = group.Select(item => new { StartDate = item.StartDate, EndDate = item.EndDate}) })
Not sure if it will work but it reads like it will.
subscriptions is just a list of your object.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the following code:
public interface IEnrollment
{
bool IsGood { get; set; }
}
public interface IEnrollmentToRegion
{
int RegionId { get; set; }
}
public class ByRegion : IEnrollmentToRegion
{
public int RegionId { get; set; }
}
public class Enrollment : IEnrollment
{
public bool IsGood { get; set; }
public ICollection<ByRegion> Regions { get; set; }
}
public class Main
{
public void DoSomething()
{
var e = new Enrollment();
if (isEnrolled(e, c => c.Any(l => l.RegionId == 10)))
{
}
}
private bool isEnrolled<T>(Enrollment enrollment, Func<ICollection<T>, bool> test) where T : IEnrollmentToRegion
{
return true;
}
}
What I'm trying to do is create the method isEnrolled that takes and object of the type IEnrollment and in this method I will do a bunch of checks to see if it return true or not. One of the things that I want to check is a collection of objects (in the above example it is simplified to only have 1 single class the ByRegion class, but in my real there are multiple Enrollment classes each with it's own separate collections under them that are of different types, but all of the types have a property called RegionId.
So I want to pass in a function that will check these various collections to see if the RegionId is in the collection. The problem that I'm having is that I get an error on the line
c.Any(l => l.RegionId == 10)) saying that it doesn't know what RegionId is. In fact when I hit the . after the l I do not get any intellisense drop down. I'm not sure why I don't get any dropdown because there is a restriction on T that T should be of the IEnrollmentToRegion type and that type has RegionId on it.
Your problem is that while a ByRegion is an IEnrollmentToRegion, an ICollection<ByRegion> is not a ICollection<IEnrollmentToRegion>. You can test this using reflection:
//Returns true
return typeof(IEnrollmentToRegion).IsAssignableFrom(typeof(ByRegion));
//Returns false
return typeof(ICollection<IEnrollmentToRegion>).IsAssignableFrom(typeof(ICollection<ByRegion>));
So you can't just specify T and let type inference take care of it for you. In fact, even if you specified the type explicitly, like:
isEnrolled<IEnrollmentToRegion>(e, c => c.Any(l => l.RegionId == 10))
You'd find that once you try to write the actual contents of isEnrolled<T>, you'd run into problems.
Here's an updated version of your code that works:
public interface IEnrollment<T> where T:IEnrollmentToRegion
{
bool IsGood { get; set; }
ICollection<T> Regions { get; set; }
}
public interface IEnrollmentToRegion
{
int RegionId { get; set; }
}
public class ByRegion : IEnrollmentToRegion
{
public int RegionId { get; set; }
}
public class Enrollment : IEnrollment<ByRegion>
{
public bool IsGood { get; set; }
public ICollection<ByRegion> Regions { get; set; }
}
public class Main
{
public void DoSomething()
{
var e = new Enrollment();
e.Regions = new List<ByRegion>() { new ByRegion { RegionId = 10 } };
if (isEnrolled(e, c => c.Any(l => l.RegionId == 10)))
{
//This line gets hit
}
}
private bool isEnrolled<T>(IEnrollment<T> enrollment, Func<ICollection<T>, bool> test) where T : IEnrollmentToRegion
{
return test(enrollment.Regions);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have three classes :
public class QData
{
public List<RData> Items { get; set; }
public List<QDay> Dates { get; set; }
}
public class QDay
{
public string Date { get; set; }
public List<RData> Details { get; set; }
}
public class RData
{
public string Name { get; set; }
public int Quantity { get; set; }
}
my list is
List<QData> myList;
What is the most effective way to sort the list (*QData type) by Date, the Date is string.
Perhaps this is what you need:
var result = myList.Select(qData => new QData()
{
Items = qData.Items,
Dates = qData.Dates.OrderBy(qDay => DateTime.Parse(qDay.Date)).ToList();
}).ToList();
With DateTime.Parse call being perhaps modified to fit to the date format in the qDay.Date property.
Here is an example that sort using the first date in the Dates list. I can't imagine why you would ever want to do this but here it is. I suspect that having Dates be a list is a mistake, in fact you only want one date there.
var sortedList = MyList.OrderBy(element => DateTime.Parse(element.Dates.First().Date));
I think this is what you actually want... ONLY ONE LIST:
public class QData
{
RData itemInfo { get; set;}
QDay dateInfo { get; set; }
}
Then your sort would look like this:
var sortedList = MyList.OrderBy(element => DateTime.Parse(element.dateInfo.Date));
var temp = (from e in myList.Dates
orderby DateTime.Parse(e.Date)
select e
).ToList();
myList.Dates = temp;