2

I want to create a sorted list of users that appear in one datatable “StatsTable”.

I need to get the userID from StatsTable and then use this to find the UserName in another datatable “UserTable”. When I have these I want to make the userID the Key and the UserName the Value in the sorted list.

I managed to get the userID and add it to the sorted list but the userName is coming through as “System.Data.EnumerableRowCollection`1[System.String]”.

What am I doing wrong? Thanks for your help.

    SortedList UserList = new SortedList();

    List<double> listofUserIDs = StatsTable.AsEnumerable()
    .Select(uid => uid.Field<double>("UserID")).ToList<double>();
    foreach (double UID in listofUserIDs)
    {
        string userName = UserTable.AsEnumerable()
            .Where(id => double.Equals(id.Field<double>("UserID"), UID))
        .Select(name => name.Field<string>("First_Name") + " " + name.Field<string>("Last_Name")).ToString();

         UserList[UID] = userName;
    }
4
  • 2
    Why are you using a double as an ID? That's a really bad idea in general.
    – Jon Skeet
    Dec 19, 2012 at 11:06
  • Not my idea, im using a database that already exists. Besides that does not answer the question. Dec 19, 2012 at 11:13
  • 1
    No, that's why it's a comment rather than an answer. You'll see a fuller answer from me elsewhere on the page. But you should take action ASAP to fix this. It will bite you sooner or later.
    – Jon Skeet
    Dec 19, 2012 at 11:20
  • Thanks, I do apprectiate the help. I definitley see the point, but there is nothing I can do about it right now, I just have to work with what I've got. Dec 19, 2012 at 11:35

4 Answers 4

4

You should use Enumerable.Join to link both tables and select what you need. In this case i would use a Tuple<int, string> whereas the int is the UserID(a UserID with decimal places makes no sense, does it?) and the string is the username:

var query = from rStats in StatsTable.AsEnumerable()
            join rUser in UserTable.AsEnumerable()
            on rStats.Field<int>("UserID") equals rUser.Field<int>("UserID")
            select new {
                UserID   = rStats.Field<int>("UserID"), 
                UserName = string.Format("{0} {1}"
                               , rUser.Field<string>("First_Name")
                               , rUser.Field<string>("Last_Name"))
            };

List<Tuple<int, string>> users = query
    .OrderBy(u => u.UserName)
    .Select(u => Tuple.Create(u.UserID, u.UserName))
    .ToList();

You can access a tuple via the Item properties:

foreach(var user in users)
    Console.WriteLine("UserID:{0} UserName:{1}",user.Item1,user.Item2);
2
  • Tim, can you please explain to me what a Tuple is? It works fine but I have never heard of it before. What is it used for? Dec 19, 2012 at 12:14
  • @DavidMuller: you can understand a Tuple<T> as a simple "class-on-the-fly". It enables to materialize things without needing to create a real class with these properties. But it also has properties Item1,Item2,ItemX and so on which are not really meaningful. So you should use them just with few properties. Dec 19, 2012 at 12:20
4

Firstly, I would avoid using double for anything requiring equality. Strings, GUIDs, and integers are all fine for IDs - doubles, not so much.

Secondly, I'd do all of this as a join in LINQ - you really don't need to iterate over every single items each time. You're turning an O(N+M) operation into an O(N + M * N) operation.

Thirdly, the reason your query isn't working is that you're simply projecting to a sequence of strings. You may happen to know that there will be exactly one match, but you need to tell the computer that. Calling ToString() on a sequence isn't going to give you anything useful. For example, you could use Single() or SingleOrDefault():

string userName = UserTable.AsEnumerable()
    .Where(id => double.Equals(id.Field<double>("UserID"), UID))
    .Select(name => name.Field<string>("First_Name") + " "
                  + name.Field<string>("Last_Name"))
    .Single();

Once you're using Single() (or any of the other calls which return a single value) you don't need ToString() at all, as the result will already be a string.

Using Single(), an exception will be thrown if there isn't exactly one result. Using SingleOrDefault(), an exception will still be thrown if there are multiple results, but you'll just get a null reference if there are no results. If it would be an error for there to be anything other than a single result, you should use Single().

0
2

This is because you are using the .AsEnumerable() which returns the source of type which returns usually a list. You can return this as a list using .ToList<string>() and select the first record or you can use FirstOrDefault(); instead of .ToList<string>() to return the first record.

0
1

The code should appere as this:

SortedList UserList = new SortedList();

List<double> listofUserIDs = StatsTable.AsEnumerable()
.Select(uid => uid.Field<double>("UserID")).ToList<double>();
foreach (double UID in listofUserIDs)
{
    string userName = UserTable.AsEnumerable()
        .Where(id => double.Equals(id.Field<double>("UserID"), UID))
    .Select(name => name.Field<string>("First_Name") + " " + name.Field<string>("Last_Name")).FirstOrDefault().ToString();

     UserList[UID] = userName;
}

You should add FirstOrDefault() before ToString(), because, select will give you a new enumerable, and not a single object!.

2
  • 2
    Calling ToString() on the result of FirstOrDefault() is a bad idea. The result will already be a string reference - but if FirstOrDefault() returns null, you'll end up with a NullReferenceException.
    – Jon Skeet
    Dec 19, 2012 at 11:12
  • It is a very preliminary solution, he should work on it, but thank you Jon!
    – Saw
    Dec 19, 2012 at 11:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.