hncl
hncl

Reputation: 2295

c# MVC XML Record Value

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.

Upvotes: 0

Views: 101

Answers (2)

Erik Dietrich
Erik Dietrich

Reputation: 6090

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.

Upvotes: 2

Oybek
Oybek

Reputation: 7243

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

Upvotes: 1

Related Questions