c# find index of in list<>

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 47027 Views - Last Post: 23 December 2013 - 09:56 AM Rate Topic: -----

#1 DukeB   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 07-October 09

c# find index of in list<>

Posted 23 December 2013 - 01:02 AM

c# 2013...
I have a list<>. It is populated. I have a variable -- strlvAssyMstrGUID. I want to search the list<> to get the index.
The list contains the same value as this variable. There should be a match.
This code does not work:
var index = retList.FindIndex(s => s.AssyMstrGUID.ToString() == strlvAssyMstrGUID);

It seems there is a conversion I am missing.
It just iterates through and returns a -1.
I have searched all over the web.. tried other things ... but nothing.
Can someone help?
Thank you..

Is This A Good Question/Topic? 0
  • +

Replies To: c# find index of in list<>

#2 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,311
  • Joined: 12-December 12

Re: c# find index of in list<>

Posted 23 December 2013 - 04:36 AM

You haven't told us what List<> is a list of..

If it were a List<String> then this works:

    List<String> fruits = new List<string>();
    fruits.AddRange(new [] {"Apple", "Pear", "Banana"});

    int index = fruits.FindIndex(s => s.Equals("Banana"));
    //Debug.Print(index.ToString());


Are you sure your values match exactly?

This post has been edited by andrewsw: 23 December 2013 - 04:38 AM

Was This Post Helpful? 1
  • +
  • -

#3 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7187
  • View blog
  • Posts: 24,357
  • Joined: 05-May 12

Re: c# find index of in list<>

Posted 23 December 2013 - 07:20 AM

I suggest using:

    int index = fruits.FindIndex(s => s == "Banana");



This is C#. We don't need that Java Equals() crutch when dealing with strings. :)/>
Was This Post Helpful? 1
  • +
  • -

#4 andrewsw   User is offline

  • never lube your breaks
  • member icon

Reputation: 6829
  • View blog
  • Posts: 28,311
  • Joined: 12-December 12

Re: c# find index of in list<>

Posted 23 December 2013 - 07:33 AM

You are right, I was wearing a Java hat :chinese:

This post has been edited by andrewsw: 23 December 2013 - 07:34 AM

Was This Post Helpful? 0
  • +
  • -

#5 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7187
  • View blog
  • Posts: 24,357
  • Joined: 05-May 12

Re: c# find index of in list<>

Posted 23 December 2013 - 07:37 AM

View PostDukeB, on 23 December 2013 - 03:02 AM, said:

I have a variable -- strlvAssyMstrGUID.

As a quick aside, the .NET Framework has a recommended naming convention and it recommends:
- not using Hungarian notation
- no abbreviations
- using camel casing for variables
- only capitalizing the first letter of common acronyms

I'm going to assume that:
- "lv" is your short hand for "local variable".
- "Assy" is for "assembly"
- "Mstr" is for "master"
- "str" is for "string"

So that variable should be named simply as assemblyMasterGuid.

Of course, the .NET naming conventions are only recommendations for public facing parts of your API. For anything that you don't plan on exposing to the world, have at it. (Although consistency tends to be a programming virtue that programmers appreciate.)
Was This Post Helpful? 2
  • +
  • -

#6 Robin19   User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: c# find index of in list<>

Posted 23 December 2013 - 07:49 AM

Based on his names, I'm guessing he's searching for a Guid on an object, not a string.

I made this short example
var list = new List<Guid>
   {
      Guid.Parse("{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}")
   };

var searchString = "{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}";

var index = list.FindIndex(g => g.ToString() == searchString);

index will be -1. Why? Because you are calling the ToString method on a Guid. How do you know if the searchString is in the correct format? Do you know that the ToString on a Guid method returns a string with only lower case letters?

The better solution is to use your string to create a Guid. Then use the overridden == operator on the Guid.
var list = new List<Guid>
   {
      Guid.Parse("{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}")
   };

var searchString = "{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}";

// notice I reference it outside the lambda so it is only created once
var searchGuid = Guid.Parse(searchString);

var index = list.FindIndex(g => g == searchGuid);

This post has been edited by Robin19: 23 December 2013 - 07:50 AM

Was This Post Helpful? 1
  • +
  • -

#7 DukeB   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 07-October 09

Re: c# find index of in list<>

Posted 23 December 2013 - 08:50 AM

View Postandrewsw, on 23 December 2013 - 04:36 AM, said:

You haven't told us what List<> is a list of..

If it were a List<String> then this works:

    List<String> fruits = new List<string>();
    fruits.AddRange(new [] {"Apple", "Pear", "Banana"});

    int index = fruits.FindIndex(s => s.Equals("Banana"));
    //Debug.Print(index.ToString());


Are you sure your values match exactly?

Yes the values match exactly. The search is on a guid produced from sql. There are strings and ints in the list.
Was This Post Helpful? 0
  • +
  • -

#8 DukeB   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 07-October 09

Re: c# find index of in list<>

Posted 23 December 2013 - 09:11 AM

View PostSkydiver, on 23 December 2013 - 07:20 AM, said:

I suggest using:

    int index = fruits.FindIndex(s => s == "Banana");



This is C#. We don't need that Java Equals() crutch when dealing with strings. :)/>/>/>

I tried that. In my original post I have
  // var index = retList.FindIndex(s => s.AssyMstrGUID == strlvAssyMstrGUID);


The code to originally populate the list is this:
   for (int i = 0; i < intRowCount; i++)
            {
                if (lvASSY.Items[i].SubItems[1].Text != "")  // lvASSY is a listview
                {
                   
                    //add item
                   var item = new Assembly ()
                    {
                    
                       Level= (string)lvASSY.Items[i].SubItems[1].Text,
                       Qty = Convert.ToInt16((string)lvASSY.Items[i].SubItems[4].Text),
                       AssyMstrGUID = (string)lvASSY.Items[i].SubItems[5].Text,
                       InventoryMstrGUID = (string)lvASSY.Items[i].SubItems[6].Text,
                       InventoryMstrGUIDMain = (string)lvASSY.Items[i].SubItems[7].Text, 
                   

                    };
                   retList.Add(item);


                }
                else if (lvASSY.Items[i].SubItems[1].Text == "")
                {
                    return;                }
               

            }


I know this code works because I save it to a sql database and then do a select. The AssyMstrGUID is null the first time. It is generated by sql upon saving the record for the first time.


then at some point I need the index. I do this..
var index = retList.FindIndex(s => s.AssyMstrGUID == strlvAssyMstrGUID);


This doesn't work.

This post has been edited by Skydiver: 23 December 2013 - 09:13 AM
Reason for edit:: Put code in code tags.

Was This Post Helpful? 0
  • +
  • -

#9 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7187
  • View blog
  • Posts: 24,357
  • Joined: 05-May 12

Re: c# find index of in list<>

Posted 23 December 2013 - 09:12 AM

See Robin19's excellent point about the output of ToString() and what you are comparing against. Any which way, his recommended solution of doing a guid to guid comparison is much better than a string to string comparison. This is because for the strings, you'll be comparing around 80 bytes (about 2 bytes per character in a string), and have the overhead of the guid to string conversion. With a guid to guid comparison, you are simply comparing 16 bytes.
Was This Post Helpful? 0
  • +
  • -

#10 DukeB   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 07-October 09

Re: c# find index of in list<>

Posted 23 December 2013 - 09:12 AM

View Postandrewsw, on 23 December 2013 - 04:36 AM, said:

You haven't told us what List<> is a list of..

If it were a List<String> then this works:

    List<String> fruits = new List<string>();
    fruits.AddRange(new [] {"Apple", "Pear", "Banana"});

    int index = fruits.FindIndex(s => s.Equals("Banana"));
    //Debug.Print(index.ToString());


Are you sure your values match exactly?

The code to originally populate the list is this:
   for (int i = 0; i < intRowCount; i++)
            {
                if (lvASSY.Items[i].SubItems[1].Text != "")  // lvASSY is a listview
                {
                   
                    //add item
                   var item = new Assembly ()
                    {
                    
                       Level= (string)lvASSY.Items[i].SubItems[1].Text,
                       Qty = Convert.ToInt16((string)lvASSY.Items[i].SubItems[4].Text),
                       AssyMstrGUID = (string)lvASSY.Items[i].SubItems[5].Text,
                       InventoryMstrGUID = (string)lvASSY.Items[i].SubItems[6].Text,
                       InventoryMstrGUIDMain = (string)lvASSY.Items[i].SubItems[7].Text, 
                   

                    };
                   retList.Add(item);


                }
                else if (lvASSY.Items[i].SubItems[1].Text == "")
                {
                    return;                }
               

            }


I know this code works because I save it to a sql database and then do a select. The AssyMstrGUID is null the first time. It is generated by sql upon saving the record for the first time.


then at some point I need the index. I do this..
var index = retList.FindIndex(s => s.AssyMstrGUID == strlvAssyMstrGUID);


This doesn't work.

This post has been edited by Skydiver: 23 December 2013 - 09:20 AM
Reason for edit:: Added additional code tags.

Was This Post Helpful? 0
  • +
  • -

#11 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7187
  • View blog
  • Posts: 24,357
  • Joined: 05-May 12

Re: c# find index of in list<>

Posted 23 December 2013 - 09:19 AM

View PostDukeB, on 23 December 2013 - 11:11 AM, said:

The code to originally populate the list is this:
Spoiler

I know this code works because I save it to a sql database and then do a select. The AssyMstrGUID is null the first time. It is generated by sql upon saving the record for the first time.

If that member is automatically generated by SQL, what is the point of line 12. Why not just assign null directly?

Can you show us how your Assembly class is declared?
Was This Post Helpful? 0
  • +
  • -

#12 DukeB   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 07-October 09

Re: c# find index of in list<>

Posted 23 December 2013 - 09:21 AM

View PostRobin19, on 23 December 2013 - 07:49 AM, said:

Based on his names, I'm guessing he's searching for a Guid on an object, not a string.

I made this short example
var list = new List<Guid>
   {
      Guid.Parse("{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}")
   };

var searchString = "{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}";

var index = list.FindIndex(g => g.ToString() == searchString);

index will be -1. Why? Because you are calling the ToString method on a Guid. How do you know if the searchString is in the correct format? Do you know that the ToString on a Guid method returns a string with only lower case letters?

if I do this string guid = retList[1].AssyMstrGUID; I get a guid with upper case just like in the sql database.
Therefore, it would seem that a search like var index = retList.FindIndex(s => s.AssyMstrGUID == strlvAssyMstrGUID);
should work. But it doesn't. I am probably over looking something very obvious.
The better solution is to use your string to create a Guid. Then use the overridden == operator on the Guid.
var list = new List<Guid>
   {
      Guid.Parse("{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}")
   };

var searchString = "{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}";

// notice I reference it outside the lambda so it is only created once
var searchGuid = Guid.Parse(searchString);

var index = list.FindIndex(g => g == searchGuid);

Was This Post Helpful? 0
  • +
  • -

#13 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7187
  • View blog
  • Posts: 24,357
  • Joined: 05-May 12

Re: c# find index of in list<>

Posted 23 December 2013 - 09:24 AM

View PostDukeB, on 23 December 2013 - 11:12 AM, said:

View Postandrewsw, on 23 December 2013 - 04:36 AM, said:

Are you sure your values match exactly?

The code to originally populate the list is this:
Spoiler

I know this code works because I save it to a sql database and then do a select. The AssyMstrGUID is null the first time. It is generated by sql upon saving the record for the first time.


How does the results of the select value make it back into retList?
Was This Post Helpful? 0
  • +
  • -

#14 DukeB   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 07-October 09

Re: c# find index of in list<>

Posted 23 December 2013 - 09:46 AM

View PostSkydiver, on 23 December 2013 - 09:19 AM, said:

View PostDukeB, on 23 December 2013 - 11:11 AM, said:

The code to originally populate the list is this:
Spoiler

I know this code works because I save it to a sql database and then do a select. The AssyMstrGUID is null the first time. It is generated by sql upon saving the record for the first time.

If that member is automatically generated by SQL, what is the point of line 12. Why not just assign null directly?

Can you show us how your Assembly class is declared?


The declaration for the assembly class is --- List<Assembly> retList = new List<Assembly>();

1) listview2 is populated from listview1. Listview1 is populated from the sql db with part numbers and their guids.
2) In the beginning of the process there is nothing saved in the db from listview2.
3) when user selects an item in listview1, it is transferred to listview2
4) User can select as many items as necessary
5) At some point user needs to save listview2
6) items are the transferred to list<> to save in db. Assymstrguid is generated at save in db and is unique. This works fine.
7) at some future point, the user will need to edit the saved record.
8) it is retrieved from the database and placed in listview2 --- this works. assymstrguid is now present from db.
9) the data is also placed in a list<> and will be used to compare the final edit in listview2 .
10 I want to change the db, which is now in list<>, to match listview2 which the user edited
11 To do this I need to determine what assymstrguids (generated in sql) in listview2 = assymstrguids in the list<>.
12) if it is found then I will update that entry in the DB.
13) if it is not found in the list, I will insert to db
14) if it is in the list<> but not in listview2, I will delete it from the db.
15) to get the index I tried var index = retList.FindIndex(s => s.AssyMstrGUID == strlvAssyMstrGUID);
This does not work ... I don't know why.
Thank you for your response.
Was This Post Helpful? 0
  • +
  • -

#15 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7187
  • View blog
  • Posts: 24,357
  • Joined: 05-May 12

Re: c# find index of in list<>

Posted 23 December 2013 - 09:48 AM

View PostDukeB, on 23 December 2013 - 11:21 AM, said:

View PostRobin19, on 23 December 2013 - 07:49 AM, said:

How do you know if the searchString is in the correct format? Do you know that the ToString on a Guid method returns a string with only lower case letters?


if I do this string guid = retList[1].AssyMstrGUID; I get a guid with upper case just like in the sql database.
Therefore, it would seem that a search like var index = retList.FindIndex(s => s.AssyMstrGUID == strlvAssyMstrGUID);
should work. But it doesn't. I am probably over looking something very obvious.


First, could you show us the declaration of the Assembly class? Is AssyMstrGUID a string or a guid?

Second, does SQL put in the curly braces when it returns guids? Does it return guids in lower case? For that matter, if AssyMstrGUID is null and only filled by SQL, can you show us the code where you pull the values from SQL and put it back into the retList?

For grins, I put together the following small program:
using System;

namespace SimpleCsConsole
{

class Test
{
    static void Main()
    {
        var s = "{AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA}";
        var guid = new Guid(s);
        Console.WriteLine(s);
        Console.WriteLine(guid);
        Console.WriteLine(guid.ToString());
#if NEVER
        // !!! Does not compile: Operator '==' cannot be applied to operands of type 'System.Guid' and 'string'
        Console.WriteLine(guid == s);
#endif
        Console.WriteLine(guid.ToString() == s);
        Console.WriteLine(guid == Guid.Parse(s));
    }
}

}


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2