ListView column highest value - c#

I don't need to sort listView I only need to get highest value from column, all values in that column are numbers.It would be nice if I could cast it to IEnumerable<int> somehow then I could use LINQ.
Update
My existing code: DrawArray is array with random numbers.I need to get max value of index.ToString() column without creating another list or array.
for (int i = 0; i < Rounds; i++)
{
ListViewItem lvItem = new ListViewItem(i.ToString());
lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, index.ToString()));
int[] DrawArray = Draw(DrawsPerRound, RoundSize);
lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, DrawArray.Aggregate("", (s, t) => s + ", " + t.ToString()).TrimStart(new char[] { ',' })));
lvItem.SubItems.Add(new ListViewItem.ListViewSubItem(lvItem, "No"));
lvItem.BackColor = Color.PaleVioletRed;
listView1.Items.Add(lvItem);
}

Might be missing some casts or something, and it is a bit ugly, but here's an idea:
var max = listView1.Items.Cast<ListViewItem>().Max(x => int.Parse(x.SubItems[0].Text));
This uses LINQ, so make sure you have using System.Linq; in your file and are using .NET >= 3.5.

ListView.Items is ListViewItemCollection inherit of IList, ICollection, IEnumerable
By linq, you can get what you want.
System.Nullable<int> max = (
from m in listView1.Items.Cast<ListViewItem>()
select int.ParseInt(m.SubItems[0].Text)).Max();

Related

Unable to change foreach to LINQ syntax

I am trying unsuccessfully to change the following loop to a LINQ expression:
int index = 0;
IList<IWebElement> divNota = new List<IWebElement>();
foreach (IWebElement element in tablaNotas)
{
divNota.Add(element.FindElement(By.Id("accion-1-celda-0-" + index + "-0")));
index++;
}
I tried using
IList <IWebElement> divNota = tablaNotas.Select(element => element.FindElement(By.Id("accion-1-celda-0-"+ tablaNotas.IndexOf(element) + "-0"))).ToList();
But tablaNotas.IndexOf(element)always returns -1, meaning the element was not found inside tablaNotas.
The string "accion-1-celda-0-"+ tablaNotas.IndexOf(element) + "-0" is meant to change to
"accion-1-celda-0-"+ 1 + "-0"
"accion-1-celda-0-"+ 2 + "-0"
"accion-1-celda-0-"+ 3 + "-0"
...
"accion-1-celda-0-"+ n + "-0"
In accordance to element's index
Any help is appreciated
In Linq some reserved word like Where, FirstOrDefault create a condition for your query and the Select reserved word can create your object that you want the Select method applies a method to elements. It is an elegant way to modify the elements in a collection such as an array. This method receives as a parameter an anonymous function—typically specified as a lambda expression.
Example: Let's look at a program where the Select extension method is applied to a string array. A local variable of array type is allocated and three string literals are used. We use Select on this array reference.
The basic method are here:
public static System.Collections.Generic.IEnumerable<TResult> Select<TSource,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, Func<TSource,int,TResult> selector);
Now! for this issue that you searched for that you can use of this code:
var divNotaResult = list
.Select((data, index) => data.FindElement(By.Id("accion-1-celda-0-" + index + "-0")))
.ToList();
In Select method do like foreach we have tow object in function data and index.
The data have each data in loop, and the index have count of loop.
var result = tableNotas
.Select((element, index) => element.FindElement(By.Id("accion-1-celda-0-" + index + "-0")))
.ToList();
Use this:
var divNota =
tablaNotas.Select((element, index) =>
element.FindElement(By.Id($"accion-1-celda-0-{index}-0")))
.ToList();

Combine two List in C# using For Each

I have two list objects in c# as mentioned below
List A
[0]
Count="0",
CountType="0",
InvTpeCode="DLX"
[1]
Count="0",
CountType="0"
InvTpeCode="STD"
List B
[0]
Count="2",
CountType="17"
[1]
Count="12",
CountType="14"
I have tried using foreach to update list a value with list b values but unfortunately i am not able to bring the desired output.
Note : Both the list are of same size only
Instead of for-loop you can also use Zip
var result = A.Zip(B, (a, b) => new Item {
InvTpeCode = a.InvTpeCode,
CountType = b.CountType,
Count = b.Count });
If the lists are the same size then a for loop will be enough:
for (int i=0; i< A.Count();i++)
{
A[i].Count = B[i].Count;
A[i].CountType = B.CountType;
}
a foreach-loop is unpractible here, i would do the following:
for(int i=0; i < A.Count(); i++)
{
A[i].Count = B[i].Count;
A[i].CountType = B[i].CountType;
}
But keep in mind this will die hard if List A is longer than B.
First assure that the lists are the same size.
var index = 0;
foreach ( ObjA itemA in listA) {
replaceValues(ObjA, listB[index]);
index++;
}
The method replaceValues should then replace the properties of ObjA with the properties of the item from listB (with the same position).
But I think it makes no sense to use an foreach here. A simple for-loop can be used - as you need the index of the current element anyway.

Get the count of values from a dictionary C#

I have a Dictionary which has an ID as the key and a list of lists as the value. I would like to get the count of how many lists are inside the list. This appears to give the correct value when I query it whilst debugging but when I go to try and access that data it only gives a count of 1 rather than 2. I'm sure it's something I'm missing but I can't put my finger on it.
Here's the count when I check it through debugging:
And here's it when I try to access that count of 2:
The whole method is:
public static List<string> getStatisticsCSVHeaders(List<Items> itemList, Dictionary<int, List<List<Statistic>>> availableStats)
{
List<string> topRow = new List<string>();
for (int i = 0; i < availableStats.Values.Count; i++)
{
topRow.Add("Phase " + (i+1));
for (int k = 0; k < itemList.Count; k++)
topRow.Add(getMetricHeader(itemList[k], true));
}
return topRow;
}
I'd like to have the number of lists inside my list as the counter for the line i < availableStats.Values.Count.
EDIT:
I should mention I've tried availableStats.Values[0].Count but this won't compile.
Debugger shows that you have a single item in your dictionary, and that item is a list with 2 elements. Because your code is taking the count of item in the dictionary you're getting 1.
To get the number of all the items in all the lists in that dictionary, try LINQ and Sum:
availableStats.Values.Sum(x => x.Count)
In your question, because value contains a list, so it is possible that it may contain a null value, so it is necessary to do a null check for values otherwise you can get an error inside your LINQ query.
var totalCount = availableStats.Values.Sum(x => x==null? 0 : x.Count);
There is one more way to get same result as follows:
var totalCount = availableStats.Sum(x => x.Value==null? 0 : x.Value.Count);

Linq keyword to Create all possible KeyValue Pairs from a set of Keys and a set of Values

Array KeyArr = {"Key1","Key2","Key3"}
Array ValArr = {"Value1","Value2","Value3"}
Here is the list of Key Value Pairs I am expecting
{Key1,Value1}
{Key2,Value1} , {Key2,Value2}
{Key3,Value1} , {Key3,Value2} , {Key3,Value3}
I can achieve it with a for loop statement but
I am just wondering if there is already a built in functionality to achieve it
where I supply the Arrays and offset for Each key...(For demo purpose I made the offset coincident with the Key position...)
If not... can anyone suggest a better and clever algorithm than the one below
int Key1Offset = 1;int Key2Offset = 2;int Key3Offset = 3;
var lst = new List<KeyValuePair<string,string>>();
for(int i=0;i<KeyArr.Count;i++)
{
if(i < Key1Offset) lst.Add(new KeyvaluePair<int,int>(KeyArr(1),ValArr(i)));
if(i < Key2Offset) lst.Add(new KeyvaluePair<int,int>(KeyArr(2),ValArr(i)));
if(i < Key3Offset) lst.Add(new KeyvaluePair<int,int>(KeyArr(3),ValArr(i)));
}
Please try to suggest a Built In function before suggesting a custom code...
Atleast a built In function that creates pairs from 2 different sets would suffice..(forget about the offset)
If you truly want all key/value pairs:
var pairs =
from key in KeyArr
from value in ValArr
select new KeyValuePair<string, string>(key, value);
If you wanted your sample output:
var pairs =
from idx in Enumerable.Range(KeyArr.Count())
from value in ValArr.Take(idx + 1)
select new KeyValuePair<string, string>(KeyArr[idx], value);

c# List Query without using Linq

I'm after some help with how to query a list and return back the index, but not using Linq. I've seen many example where Linq is used, but the software I'm writing the query into doesn't support Linq. :(
So example to get us going:
List<string> location = new List<string>();
location.add(#"C:\test\numbers\FileName_IgnoreThis_1.jpg");
location.add(#"C:\test\numbers\FileName_IgnoreThis_2.jpg");
location.add(#"C:\test\numbers\FileName_ImAfterThis_3.jpg");
location.add(#"C:\test\numbers\FileName_IgnoreThis_4.jpg");
location.add(#"C:\test\numbers\FileName_ImAfterThis_5.jpg");
So this list will be populated with probably a few hundred records, what I need to do is query the list for the text "ImAfterThis" then return the index number location for this item into a string array but without using Linq.
The desired result would be 2 and 4 being added to the string array.
I was thinking of doing a for loop through the list, but is there a better way to achieve this?
List<int> results = new List<int>();
int i = 0;
foreach (string value in location)
{
if (value.Contains("IAfterThis"))
{
results.Add(i);
Console.WriteLine("Found in Index: " + i);
}
i++;
}
Console.ReadLine();
Thanks in advance.
If you want to get just the first occurrence you could simply use the IndexOf() method.
If you want all occurrences of string "whatever" then a for loop would certainly work for you. For the sake of argument here I've capture the indexes in another list:
string MyString = "whatever";
List<int> indexes = new List();
for (int i = 0; i < location.Count; i++)
{
if (location[i] == MyString)
{
indexes.Add(i);
}
}

Categories

Resources