0

I have an xml file:

<profiles>
  <profile username="user4" fullname="Full Name" />
 </profiles>

I am trying to retrive the value of the fullname, here is what I tried:

public List<string> GetFullName(string username)
{
    List<Profile> list = null;
    try
    {
        list = (from t in ProfileList
                where t.UserName == username
                select t).FirstOrDefault();
    }
    catch { }
    List<string> userFullName = new List<string>();
    if (list != null)
    {
        foreach (Profile t in list)
        {
            userFullName.Find(t.FullName);
        }
    }
    return userFullName;
}

FirstOrDefault gives an error!
Thanks in advance.

3
  • Dude, are you aware you have global variables in your code? Also, like the compiler, we can't infer the type of ProfileList. Commented Feb 23, 2012 at 22:26
  • FirstOrDefault gives an error Is that all? What is ProfileList? what error do you exactly get ? Commented Feb 23, 2012 at 22:28
  • @linkerro Actually the ProfileList type can be inferred by us. It should be IEnumerable<T> where T has a properties UserName and FullName. )) Commented Feb 28, 2012 at 7:41

2 Answers 2

2

FirstOrDefault() is an extension method, which means that it's basically similar in concept to doing something like

var myList = new List<int>() { };
int myValue = StaticUtilsClass.FirstOrDefault(myList);

Now, if you look at FirstOrDefault documentation, notice that it throws a null argument exception when you pass in a null parameter.

What this means is that

List<int> myList = null;
myList.FirstOrDefault();

will throw an exception.

So, anytime you call x.FirstOrDefault(), and encounter a problem (i.e. an "error") the first thing to check is whether x, in this case, your query, is returning null.

From there, I would take a look at the fact that FirstOrDefault() is going to return a single entity, but you're setting it equal to a List<Profile>. Unless your ProfileList is an enumeration of List<Profile>, that's going to be a problem as well.

That should get you started anyway. Beyond that, it'd be helpful to know what ProfileList is and where it's declared.

Sign up to request clarification or add additional context in comments.

Comments

1

I'd rather rewrite your code like this

    public String GetFullName(string username)
    {
        var targetObject = (from t in ProfileList
                    where t.UserName == username
                    select t).FirstOrDefault();

        if (targetObject != null) return targetObject.FullName;
        throw new Exception("Target user is not found");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.