简体   繁体   中英

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);

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM