I have this code:
public ActionResult DeleteBehandling(int id)
{
AppointmentDiary _ad = new AppointmentDiary();
var beh = _db.Behandlingar.Single(k => k.BehandlingarId == id);
foreach (var item in _ad.BehandlingarId)
{
if (_ad.BehandlingarId == id)
{
return View();
}
}
_db.Behandlingar.Remove(beh);
_db.SaveChanges();
return RedirectToAction("BehandlingarNy");
}
_ad.BehandlingarId is a column in my database containing int. Now, I want to loop through this column to see if I get a match with the input. I get this error:
foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public definition for 'GetEnumerator.
How do I get past this?
Thanks!
_ad.BehandlingarId is an int column as you say.
So you should not iterate over it.
Instead you should use something like this
foreach (var item in _ad)
{
if (item.BehandlingarId == id)
{
return View();
}
}
You're trying to loop over something that's not a collection (BehandlingarId is an int) - at a guess, i'd suggest you need to change your loop to this:
foreach (var item in _ad)
{
....
Related
This is my firebase database structure
Database Structure
In the child, there are values , Name, Country, Age and Uid. The Uid is the focus in my question.
I am try to fetch the children of the node (Chat) based on the current logged in user.
I am basically trying to do a comparison here that, firebase should get me children who only have the Uid = user.uid. i.e the current logged in user. I thought Equals() could do the trick but i get an error with the cast.
The error points at this line var items = snapshot.Children?.ToEnumerable<DataSnapshot>().Equals(user.uid).ToString;
public void OnDataChange(DataSnapshot snapshot)
{
var items = snapshot.Children?.ToEnumerable<DataSnapshot>().Equals(user.uid).ToString;
var key = snapshot.Key;
HashMap map;
foreach (DataSnapshot item in items)
{
}
Console
my snapshot test: DataSnapshot { key = Chat, value = {-KomfGbZxCGESgyo1PFT={Name=Testing , Ref=7YB3mxMRXxW4lzhbhxi1bx7K4Pf1,
}, -KomcJyR5dCxFucJSB0I={Name=Hi, Ref=K6TEpccn1TbB32T8ThFsYnIl6Wm2, }} }
If you want to filter the user based on Ref attribute, I suggest you make an if-statement inside foreach loop to filter the item:
public void OnDataChange(DataSnapshot snapshot)
{
var items = snapshot.Children?.ToEnumerable<DataSnapshot>();
HashMap map;
foreach (DataSnapshot item in items)
{
//filter the user first
map = (HashMap)item.Value;
string userId = map.Get("Ref")?.ToString();
if (userId!=null&& userId == user.uid)
{
//do what you want to do here.
}
}
When you use ToEnumerable, the type of returned objects is DataSnapshot and it cannot be compared to user.uid. You might want to use linq to grab what you wants. something like:
var items = snapshot.Children?.ToEnumerable(x=> x.uid == user.uid)
I have two lists of objects: List<One> & List<Two> and I want to achieve the following.
For each One.Id:
if there's a matching Id in Two.Id, do nothing
else if there are no matching Ids in Two.Id, do something
I tried with iteration inside iteration, but couldn't find a suitable solution.
Thanks in advance.
You can use LINQ's Any() method to check for presence of matching items:
foreach (var one in listOne) {
if (!listTwo.Any(two => two.Id == one.Id)) {
// No matches
}
}
I would use Any() in a dedicated function like this:
bool HasMatches(List<One> ones, List<Two> twos)
{
foreach (var item in ones) {
if (!twos.Any(other => other.Id == item.Id))
return false;
}
return true;
}
You should finish the search once you have found no match for the current item.
foreach(var item1 in list1)
{
if(list2.Any(item2=>item2.Id== item1.Id))
{
//do nothing
continue;
}
// do something
}
you can do some thing like this
List<one> a = new List<one>;
List<two> b = new List<two>;
foreach( l in a)
{
if(b.Any(x=>x.id == l.id)){
//do something
}
else{
//do something
}
}
You can use Contains like this.
bool isContainId = List<one>.Contains(two.Id);
if (isContainsId)
{
// do something
}
else
{
// do something
}
I`m trying to make a query in robomongo but there seems to be too many results in the query.
List<DataObject> list = collection.FindAs<DataObject>(Query.EQ("Item1", "Value1")).ToList();
foreach (DataObject item in list)
{
//Do Something
}
From what i read, i would need to use MongoCursor, but I couldnt find a good example, is there iterate through everything using batches of 1000?
Something like:
MongoCursor<DataObject> cursor = collection.FindAs<DataObject>(Query.EQ("Item1", "Value1"));
int batchNumber = 1000;
List<DataObject> list;
while(list = cursor.getBatch(batchNumber);)
{
foreach (DataObject item in list)
{
//Do Something
}
}
Now I understood i could easily solve this if i dont save it in a list before the foreach by doing :
foreach (DataObject item in collection.FindAs<DataObject>(Query.EQ("Item1", "Value1")))
{
//Do Something
}
This was solved by not saving the result in a list before the foreach. Like this
foreach (DataObject item in collection.FindAs<DataObject>(Query.EQ("Item1", "Value1")))
{
//Do Something
}
hi I have code like this
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
kalimatSql = kalimatSql;
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows)
while (Global.reader.Read())
{
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
Global.dbCon.Close();
foreach (int id in idQuestions)
messageBox.Show(id.ToString());
I try to make edit it to function (class) so I can call it many times like this
private int sqlReader(string kalimatSql)
{
int sqlReader(string kalimatSql){
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows)
while (Global.reader.Read())
{
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
Global.dbCon.Close();
foreach (int id in idQuestions)
return id;
}
but it's not working because not all code paths return a value... I wonder what's the correct way to do it?
There are two issues with this last part of your code:
foreach (int id in idQuestions) {
return id;
}
}
The primary issue here is that you're not returning anything if idQuestions is empty (which is why you're receiving this error). But even if it's not empty, your code is returning the first time you enter the foreach's body, thus returning only the first element from the list of ids.
I'm assuming you want to return the entire list of ids, which is convenient because you already have them all inside of a List<>. Simply change your code to this:
return idQuestions;
}
The complete method should look like this (note the method signature):
private List<int> sqlReader(string kalimatSql) {
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
}
Global.dbCon.Close();
//return the ids
return idQuestions;
}
this error occurred because, what will happened (or returned) when your last 'foreach' loop runs zero time?, in other sense what value should your code return when your 'idQuestions' has zero length?
in order to get rid of this, you change this code as
if(idQuestions.Count > 0)
{
foreach (int id in idQuestions) {
return id;
}
}
else
return -1;
The last line:
foreach (int id in idQuestions) {
return id;
}
Is the same as saying if (idQuestions.Count > 0) { return idQuestions[0]; }.
The error is because you are not returning a value at the end of your code flow. There are many ways to fix this in your case, but you need to figure out what a 'default' value would be (like null or -1.
You could do something like the following:
return (idQuestions.Count > 0 ? idQuestions[0] : -1)`
if a -1 is a valid return value, or if your intent was to return the whole array (or null if invalid) you could something like this:
return (idQuestions.Count > 0 ? idQuestions : null)
hope that can help
It seems very wrong to put return inside a foreach loop.
if you have multiple result ,you can return IEnumerable
foreach(int id in idQuestions)
yield return id;
It seems from your code that you are trying to fetch some ids from your data store. In that case, according to your code, it will return only id of first element returned from your data store. If I have understood your question properly, the code should be like this,
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
}
Global.dbCon.Close();
return idQuestions;
What if there isnt any elements in idQuestions. foreach will never get executed.
I am supposing you are returning single integer value from ur function
so after foreach return default int. You got ur algorithm alltogether wrong. Only first Id will be returned if u implement second code version
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
int deft=0;
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
}
Global.dbCon.Close();
foreach (int id in idQuestions) {
return id;
}
return deft;
The issue there is that your one and only return statement is inside a foreach loop and the contents of that loop will never be executed if the list you enumerate is empty. Why do you have a loop at all if you're going to return the first value in the list anyway though?
I have this:
public class accounts
{
private string mName;
private string mEmail;
private string mAddress;
public accounts(string Name,
string Email,
string Address)
{
this.mName = Name;
this.mEmail = Email;
this.mAddress = Address;
}
}
then, somewhere else, I create this:
private static List<accounts> mlocalaccountList = new List<accounts>()
then I fill it like this:
mlocalaccountList.Add(new accounts("John Smith","johnsmith#mail.com","CA USA"));
Now, everything is OK, except, how can I access the list<> items??
You can access them in a foreach loop:
foreach (var item in mlocalaccountList) {
...
}
however, since all members are private you cannot access them at all. Consider making properties for the private members or making them public.
You can also access them by index:
mlocalaccountList[0]
is the first item in the list.
By indexer like an array
mlocalaccountList[0]
foreach (accounts a in mlocalaccountList) { /* do something */ }
will iterate through the list.
Try mlocalaccountList[0] or
foreach (accounts acct in mlocalaccountList)
{
// Do something with acct
}
I would recommend using a foreach statement or just access by using an index variable mlocalaccount[index]
You can iterate over them:
foreach (var item in mlocalaccountList)
{
// do stuff with item
}
You can use LINQ:
var usaItems = mlocalaccountList.Where(a => a.Address.Contains("USA"));
// assuming you implement a public property for Address
Here's a link to the List<T> MSDN page. The Members page lists all the methods and properties that you have available. You can find help on ForEach for example.
The MSDN library (http://msdn.microsoft.com/en-us/library/) is an invaluable source of information on the classes and their members.
Just combining the list of everyone's answers here so far:
Use an indexer into the list: mlocalaccountsList[i] will return the i'th element (0-based index, of course)
Iterate over the list using a loop. foreach(var account in mlocalaccountList) will easily provide you with each element in turn.
Use a LINQ query to filter out a specific element in the list. LINQ has two different styles of writing queries:
var result = mlocalaccountList.Where(a => a.Name == "John Smith"))
// or
var result = from a in mlocalaccountList
where a.Name == "John Smith"
select a;
Use a foreach statement:
foreach (accounts acc in mlocalaccountList)
{
... do something with acc
}
Though I don't program in C#, I believe it is: mlocalaccountList[index] where index is an int.