tequilaras
tequilaras

Reputation: 279

c# get a specific element of a HashSet

I want to get an element of a HashSet only if it contains a specific string in it. i tried the code below, but i dont get anything... like no matching. but this cant happen cause the UnKnown counter is always 0.

if (!IsbnAuth.Contains(RecTitle))
{
    Unknown++;
}
else
{
    for (int i = 0; i < IsbnAuth.Count(); i++)
    {
        if (IsbnAuth.ElementAt(i).Contains(RecTitle))
        {
            System.Console.WriteLine(IsbnAuth.ElementAt(i));
            //isbn = IsbnAuth.ElementAt(i).Substring(0, IsbnAuth.ElementAt(i).IndexOf("\t"));
            isbn = IsbnAuth.ElementAt(i).Split(' ')[0];
            break;
        }
    }
}

Any ideas? the problem is not at the RecTitle cause even if it was just a single char instead, the result would be the same. IsbnAuth is the HashSet.

EDIT: IsbnAuth declaration

    HashSet<String> IsbnAuth = new HashSet<String>();
    foreach (String line in IsbnAuthors)
    {
        IsbnAuth.Add(line.Trim());
    }
    System.Console.WriteLine(IsbnAuth.Count);

Upvotes: 2

Views: 16372

Answers (2)

Fischermaen
Fischermaen

Reputation: 12458

It seems to me that you are storing mulitple informations held in one string in your Hastable. I would do it in that way:

public class Info
{
    public string ISBN { get; set; }
    public string Title { get; set; }
}

later in code:

List<Info> isbnAuth = new List<Info>();
foreach (String line in IsbnAuthors)      
{ 
    isbnAuth.Add(new Info { ISDN = line.Split(' ')[0], Title = line.Split(' ')[1] });
}

You can search an item like this:

var itemFound = isbnAuth.FirstOrDefault(item => item.Title == RecTitle);
if (itemFound != null)
{
    isbn = itemFound.ISBN;
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500495

This is the first problem:

if (!IsbnAuth.Contains(RecTitle))
{
    Unknown++;
}

That checks whether the set contains the whole string, as a complete element. It sounds like it doesn't.

I suspect you really want:

bool found = false;
foreach (String element in IsbnAuth)
{
    if (element.Contains(RecTitle))
    {
        isbn = element.Split(' ')[0];
        found = true;
        break;
    }
}
if (!found)
{
    Unknown++;
}

Or even better:

string isbn = IsbnAuth.Where(x => x.Contains(RecTitle))
                      .Select(x => x.Split(' ')[0])
                      .FirstOrDefault();
if (isbn == null)
{
    Unknown++;
}

It's worth being aware that a HashSet is in a fundamentally unpredictable order - so if there are multiple matches here, you'll end up with an arbitrary result. Is that really what you want?

Upvotes: 9

Related Questions