0

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);
}
formatc
  • 4,261
  • 7
  • 43
  • 81

2 Answers2

1

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();
bitoshi.n
  • 2,278
  • 1
  • 16
  • 16
  • Lose the 'var' in your query which souldn't be there, and you will get Could not find an implementation of the query pattern for source type 'System.Windows.Forms.ListView.ListViewItemCollection'. 'Select' not found. Consider explicitly specifying the type of the range variable 'm'. – formatc May 17 '12 at 18:48
  • 1
    You need to explicitly specify (cast to) the type of the variable m whenever the compiler can't infer its actual type. Therefore, listview1.Items.Cast() should solve the problem. – Daniel May 17 '12 at 19:36
1

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.

Tim S.
  • 55,448
  • 7
  • 96
  • 122