retrieving Odd values from a List collection and saving them as GUID c#

I'm trying to retrieve odd values in a List of strings and convert them into a Guid Object. Here is what i came up with

        Guid oGuid = new Guid();
        string objectName = string.Empty;

        for (int i = 0; i < lst_objectName_Guid.Count; i++)
        {
            if (i % 2 != 0) //The GUID values are in the Odd-Numbered Indexses
            {
                oGuid = new Guid(lst_objectName_Guid[i]); //Convert the GUID Values from string to Guid
            }
            else
            {
                objectName = lst_objectName_Guid[i];    //Assign the objectName Values into a string variable
            }

            Console.WriteLine(objectName);
            Console.WriteLine(oGuid);

The problem is now that always it displays a set of (0) Zero's as the first Guid is retrieved and I get a "Object does not exist" when I check if the Object is locked or not.(I get this on every even object that is tested)

Can anybody tell me what's happening and why? and if there is a better way to retrieve odd_numbered indexes and store them as GUID

I'm pretty sure that the odd indexes hold the Guid Values as strings. I printed out the List and made sure of that

Thanks

1
задан Reda 30 August 2010 в 09:39
поделиться

3 ответа

Я думаю, что ответ Грценио правильный, но я не думаю, что вы понимаете, почему. Чтобы уточнить, возьмем этот простой пример:

string Part1 = "";
string Part2 = "";

for (int i = 0; i < 2; i++)
{
    if (i == 0)
    {
        Part1 = "Set on first iteration";
    }
    else
    {
        Part2 = "Set on second iteration";
    }
}

Вот, это именно то, что вы сделали. На первой итерации цикла (i==0) вы только устанавливаете первую переменную Part1. Таким образом, вывод будет следующим:

Part1: "Set on first iteration"
Part2: ""

На второй итерации (i==1), Часть2 будет иметь установленное значение, а затем будет выведено:

Part1: "Set on first iteration"
Part2: "Set on second iteration"

Итак, принимая ваш пример:

Guid oGuid = new Guid(); // Equals all 0s by default
string objectName = string.Empty;

objectName устанавливается на первой итерации, но oGuid не . Следовательно, почему oGuid остается "все нули" (Guid.Empty).

Итак, вы должны использовать следующий код:

Guid oGuid = new Guid();
string objectName = string.Empty;

for (int i = 0; i < lst_objectName_Guid.Count; i+=2)
{

    // Notice how BOTH variables are assigned
    oGuid = new Guid(lst_objectName_Guid[i]); 
    objectName = lst_objectName_Guid[i + 1];

    // So when they're written to the console, they both have values
    Console.WriteLine(objectName);
    Console.WriteLine(oGuid);

}
1
ответ дан 2 September 2019 в 21:50
поделиться

Если вы можете использовать Linq, попробуйте следующее:

lst_objectName_Guid.Select((item, index) => index % 2 != 0 ? new Guid(item) : Guid.Empty);

Это использует перегруженную версию .Select(), которая включает индекс. Вы получите iEnumerable из Guid с Guid.Empty для не-Guids.

Кроме того, вы можете использовать метод TryParseGuid (вам придется создать свой собственный/найти такой, как этот), чтобы убедиться, что они на самом деле Guid .

0
ответ дан 2 September 2019 в 21:50
поделиться

Вы слишком часто печатаете свои объекты, попробуйте этот подход:

    Guid oGuid = new Guid();
    string objectName = string.Empty;

    for (int i = 0; i +1 < lst_objectName_Guid.Count; i+=2)
    {
        objectName = lst_objectName_Guid[i];
        oGuid = new Guid(lst_objectName_Guid[i+1]); //Convert the GUID Values from string to Guid


        Console.WriteLine(objectName);
        Console.WriteLine(oGuid);
    }
1
ответ дан 2 September 2019 в 21:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: