For specific number of times - c#

I am trying to do something like this in my HTML:
#foreach (var item in Model) {
However rather than do it for every entry I only want the first 6 items in the model. Does anyone know the syntax? Have tried a few with no sucess.

How about using Take LINQ method
#foreach (var item in Model.Take(6))
don't forget to add namespace System.Linq in your view

You could use a simple for loop.
e.g. for(int i = 0; i < 6; i++)

You can use Enumerable.Take<TSource> Method: Returns a specified number of contiguous elements from the start of a sequence.
Eg.
#foreach (var item in Model.Take(5)) {
Refer:
Enumerable.Take Method

Related

Index was out of range error. But when i excecute item.count() returns 1

I'm having issues with razor, I'm trying to access the first element of a list. But when I try to cast an element with item2.hijos[0].ruta, I get an error.
But when I use item2.hijos.count(), it returns 1. So there is an element but somehow razor doesn't want me to access it.
Here is my code. items2.hijos.first() doesn't work either.
foreach (var item in Model)
{
<li id="#(item.CNombreManual)" onclick="mostrarEsconderHijos(this.id)" class="list-group-item-heading">#(item.CNombreManual)</li>
foreach (var item2 in item.hijos)
{
<li id="_#(item.cNombreManual)" class="list-group-item" style="tex-align:left; display:none">
#(item2.CNombreManual)
#Html.ImageActionLink("Ver PDF", "Descargar", "Manual", new { NombreArchivo = item2.hijos[0].Ruta }, null, "~/imgs/LecturaPdf.png")
</li>
}
}
Just check whether you have the items in the array item2.hijos[] before using the array. It could be printing the values for the first few records and then throwing an error where there is no element. So it can be happening for any hijos array of item2 of item. Just ensure you check for the array size before using it.
item2.hijos[0].Ruta // replace this with the following
item2.hijos.Length > 0? item2.hijos[0].Ruta : 0
I think you can even do shorter. item2.hijos[0]?.Ruta ?? 0
I don't know the details of your model, but the problem is that you're iterating (foreach) of item's hijos, but then accessing of item2's hojos.
I think you want to access item2.Ruta:
foreach (var item2 in item.hijos)
{
(...) item2.Ruta // not item2.hijos[0].Ruta
If you actually need to access item2.hijos[0].Ruta then you need check if it exists first.
You can do that using:
item2.hijos.Count()
item2.hijos.Any()
You could also use item2.hijos.FirstOrDefault()?.Ruta (see Enumerable.FirstOrDefault Method).
Btw. the whole hijos could also be null, so it may be necessary to check if the whole collection (item2.hijos).
Finally, you may want to add another foreach for item2.hijas rather than access element 0.

How to control outputting data in #foreach

How can I control the number of outputting data in #foreach section?
For ex, in #foreach(var x in Model){} I want to get only first 10 data in that model, what am I supposed to do?
Assuming your Model is a collection type(Ex :IEnumerable<T>), You can use LINQ Take method.
#model IEnumerable<SomeViewModel>
#{ var tenItems = Model.Take(10);} // Get the 10 items from the collection
#foreach (var x in tenItems)
{
<p>#x.Name</p>
}
Also, If you want you can order by the results before taking the 10 items,
#{ var tenItems = Model.OrderBy(s=>s.SomePropertyOfYourClass).Take(10);}

Unable to use Viewbag List Items in Razor foreach loop

I have an Images table linked to an Item table (one Item can have many Images). They are linked by the Item Id.
I want to return all images for an Item on the details page. I have been trying to use a Viewbag to achieve this (below).
Controller:
ViewBag.imageFile = (from f in storeDB.Images
where f.ItemId == id
select f.ImageURL).ToList();
View:
#foreach (var image in ((List<string>)ViewBag.imageFile))
{
#ViewBag.imageFile
}
The above will return 'System.Collections.Generic.List`1[System.String]' for each ImageUrl.
I believe the issue is that an object is being return rather than the actual List item string value but cannot figure out how to convert it to the string I need. The plan is to edit this foreach to create an img link for each URL.
I also have the following Viewbag (testing to see I was able to get the Urls at least):
ViewBag.imageURL = string.Join(",", ViewBag.imageFile);
The above returns the correct URLs but they are all in one string separated by a comma.
Appreciate any help.
Inside the loop in the view, you should use the loop variable:
#foreach (var image in ((List<string>)ViewBag.imageFile))
{
#image
}
ViewBag.imageFile is the complete list and will always be, even inside the loop. The image loop variable will be the current item from the list on every turn of the loop.
ViewBag does not require a type casting:
#foreach (var image in ViewBag.imageFile))
{
#image
}

replacing an object in listview with new one?

I have a listview with few items. I am using foreach loop to check if there is a match. The code I am using looks like this:
foreach (ListViewItem test in listView1.Items)
{
if (test.SubItems[1].ToString() == item.SubItems[1].ToString())
{
test.Tag = item.Tag;
}
}
What I am trying to do is, check the 2nd index and if there is a match replace the old item 'test' with the new one 'item'.
Apparently there is no change in the listview. Is the way I am replacing the object wrong?
you can clone the item and assign directly to the list view item. but you need to change foreach loop to for loop.
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].SubItems[1].ToString() == item.SubItems[1].ToString())
{
listView1.Items[i] = (ListViewItem)item.Clone();
}
}
You have updated the Tag only. You need to change test.SubItems[0], test.SubItems[1],... to see the changes.
Or you could remove old item and insert new item by using listView1.Items.Remove(...) or listView1.Items.RemoveAt(...) and listView1.Items.Insert(...). But if you need to pay account of performance you should use the first algorithm (changing test.SubItems[i]).

Foreach doesn't go through all items?

I have this code:
foreach (var item in ListView1.Items)
{
ListView1.Items.Remove(item);
ListView21.Items.Add(item);
}
the loop stops at half of the items?
Any idea?
EDIT
Well, maybe it's my mistake, I need to clarify that this is UltraListView control from Infrajistics, where I can't add item to another list unless I remove it or clone it from the original list.
But thanks, most of the comments regarding do not modify the list within the loop were correct, so this code works:
foreach (var item in listView1.Items)
{
var i = item.Clone(true);
listView2.Items.Add(i);
}
listView1.Items.Clear();
Thanks,
You cannot modify iterated collection, it should die with exception (or in undefined behavior).
Try making a copy of the array:
foreach (var item in ListView1.Items.ToArray())
{
ListView1.Items.Remove(item);
ListView21.Items.Add(item);
}
EDIT:
in fact, your example code can be achieved by writing:
ListView21.Items.AddRange(ListView1.Items);
ListView1.Items.Clear();
(which in fact isn't EXACTLY what you are doing, but gives the same result and I think it won't bother you having the same content in both listviews for a moment). The latter is supported since .NET2.0, first solution requires linq, and therefore .NET3.5.
You are modifying the collection you are looping through. Try using a for statement from top to bottom (from the item with the highest index to 0).
for (int i = ListView1.Items.Count - 1; i >= 0; i--)
{
var item = ListView1.Items[i];
ListView1.Items.Remove(item);
ListView21.Items.Insert(0, item);
}
It will cause a runtime exception, complaining that you cannot modify the collection while iterating through it. You have to use for loop instead.
for(int index = Items.Count; index > 0; index--)
{
.......
// use Add and RemoveAt
}
EDIT : As mentioned by others. If you just need to move items from one collection to the other. AddRange and Clear will be better.
Do you get any exception or error message? Looping in a collection and remove items from the same collection is always a bad idea.
This looks like the WinForms list view control, so:
ListViewItem[] items = ListView1.Items.ToArray();
ListView1.Items.Clear();
ListView21.Items.AddRange(items);
Why just not CopyTo() to new list and then Clear() items?
You are looping through all items, removing all of them, then adding them to another list. As others have commented, you cannot remove items from a list in a for-each. Why not looping through all items to add them to your other list, and then remove them all in one go?
foreach (var item in ListView1.Items)
{
ListView21.Items.Add(item);
}
ListView1.Items.Clear(); // remove all
PS: is this an ASP.NET listview or a WinForms listview?
That's because you're changing the collection inside the loop.
Use a normal for loop as follows:
for(int i=0; i < ListView1.Items.Count-1; i++)
{
ListView21.Items.Add(ListView1.Items[i]);
ListView1.Items.RemoveAt(i);
}

Categories

Resources