Archive for category LINQ

Sorting by two values

I had a list of objects that were created in code, and I wanted to sort by City, then by Name. Yes, a two-value search. My basic class looked like this:

public class User {

      public string Name { get; set; }

      public string City { get; set; }

}

Somewhere along the line of my awesome application, a List<User> gets populated with all kinds of wonderful values. Imagine Willy Wonka and the Chocolate Factory, but way more amazing:

 List<User> stuff = … // Amazing things happen here.

 After the above line, my data looks something like this:

stuff[0] = {“Scott”,”Lansing”};
stuff[1] = {“Dave”,”Lansing”};
stuff[2] = {“Tim”,”Columbus”};

The results I want are:
Tim
Dave
Scott

In order to work this beautiful thing, I only needed one line of c#:

List<User> results = stuff.OrderBy(s => s.City).ThenBy(s => s.Title).ToList();

C’est tout! Sacre bleu!

2 Comments

SingleOrDefault Sequence contains more than one matching element

I was receiving an exception “SingleOrDefault Sequence contains more than one matching element” when trying to return a single object from a List. Here is a little demonstration of what was happening. First, my very useful, real-life class:

    public class Testing
    {
        public string Name{ get; set; }
        public int ID { get; set; }

        public Testing(string name, int id)
        {
            Name = name;
            ID = id;
        }
    }

So in the Page_Load event, I populate my useful, real-life class with some very important data. This is very secure data, so don’t share it with anyone:

        protected void Page_Load(object sender, EventArgs e)
        {
            List<Testing> testing = new List<Testing>(){};
            testing.Add(new Testing("san francisco",1));
            testing.Add(new Testing("toronto",2));
            testing.Add(new Testing("chicago", 3));

            var item = testing.SingleOrDefault(i => i.ID == 1);
        }

If all my IDs are unique, no problem, this will run successfully. If, however, I have duplicate IDs, then problem will arise. So if I change my code to that below, adding a duplicate ID:

        protected void Page_Load(object sender, EventArgs e)
        {
            List<Testing> testing = new List<Testing>(){};
            testing.Add(new Testing("san francisco",1));
            testing.Add(new Testing("toronto",2));
            testing.Add(new Testing("chicago", 3));
            testing.Add(new Testing("new york", 1));

            var item = testing.SingleOrDefault (i => i.ID == 1);
        }

Bong, I get the error “SingleOrDefault Sequence contains more than one matching element”.
The way I got around this was to replace SingleOrDefault with FirstOrDefault, and my code ran correctly:

        protected void Page_Load(object sender, EventArgs e)
        {
            List<Testing> testing = new List<Testing>(){};
            testing.Add(new Testing("san francisco",1));
            testing.Add(new Testing("toronto",2));
            testing.Add(new Testing("chicago", 3));
            testing.Add(new Testing("new york", 1));

            var item = testing.FirstOrDefault (i => i.ID == 1);    
        }

Leave a comment

The LINQ RemoveAll call

Another rinky dink LINQ issue. I needed to remove some items from a collection, and lo, I wanted to do it with LINQ because ladies love LINQ experts – that’s just how it is.

So I have my collection of objects:

     List<Order> OrderItems = DBClass.GetStuff(CustomerId);

And I use the handy dandy RemoveAll function to heartlessly delete all records matching the Status field of my Order class:

     OrderItems.RemoveAll(item => item.Status == "Approved");

Am I the only one who feels cool when they do LINQ stuff? I need to get out more.

Leave a comment

Sort with multiple fields in LINQ

Those crazy users – they wanted to sort by two fields! What madness is that? So I dig into the source and the original code was sorting with LINQ. Being a sheep, I decided to do the same thing. But how? Through the miracle of the ThenBy operator.

So in this example, I wanted to order by City, then Zip Code.  Assuming that my items collection contains objects with City and ZipCode fields:

List<Address> items = DBStuff.GetAddresses(bizID);
GridView1.DataSource = items.OrderBy(i => i.City).ThenBy(i => i.ZipCode);

See MSDN for more info.

Leave a comment

Error: Row not found or changed

There I was, minding my own business, when I got this message:

Row not found or changed.

Apparently, my LINQ to SQL objects were rebelling, and I needed to put the smackdown on them. (I found not one, but two useful posts on it.) I did that by adding the “UpdateCheck = UpdateCheck.Never” to each of the properties in the designer.cs file, under the dbml file, that declared all the wonderful things inside my object model. So here is an example of one of the properties after I made the change:

[Column(Storage = "_ImageText", UpdateCheck = UpdateCheck.Never, DbType = "NVARCHAR(1000)", CanBeNull = false)]
  public string ImageText
  {
   get
   {
    return this._ImageText;
   }
   set
   {
    if ((this._ImageText != value))
    {
     this.OnImageTextChanging(value);
     this.SendPropertyChanging();
     this._ImageText = value;
     this.SendPropertyChanged("ImageText");
     this.OnImageTextChanged();
    }
   }
}

Leave a comment

Deleting Excel worksheets with VB.NET and LINQ

I never claim that the way I do it is the best way…

I created code to insert a worksheet into Excel for each user in the query. But the focus of this post is deleting those default sheets that Excel starts with, Sheet1, Sheet2, and Sheet3. When I tried to delete them at the beginning of my code, I was graciously given this friendly COMException:

A workbook must contain at least one visible worksheet.

No worries, I’ll just do it at the end of the process. I came up with two ways. First, the easy, so un-cool way to do it: Just count backwards from the worksheet count:

Dim bkWorkBook As Excel.Workbook = DirectCast(oXL.Workbooks.Add(), Excel.Workbook)
Dim shWorkSheet As Excel.Worksheet = DirectCast(bkWorkBook.Sheets("Sheet1"), Excel.Worksheet)
'Code to populate the worksheets
Dim Counter As Integer = bkWorkBook.Sheets.Count
CType(bkWorkBook.Sheets(Counter), Excel.Worksheet).Delete()
CType(bkWorkBook.Sheets(Counter - 1), Excel.Worksheet).Delete()
CType(bkWorkBook.Sheets(Counter - 2), Excel.Worksheet).Delete()

Oh, that’s too easy, though. Isn’t there some way I could use some cool LINQ extension method to do this? You betcha. This is the round-about way I came up with using OrderByDescending:

Dim SheetName As String = String.Empty
Dim SheetIds As New List(Of Integer)
For i As Integer = 1 To bkWorkBook.Sheets.Count
            SheetName = CType(bkWorkBook.Sheets(i), Excel.Worksheet).Name
            If SheetName = "Sheet1" OrElse SheetName = "Sheet2" OrElse SheetName = "Sheet3" Then
                SheetIds.Add(i)
            End If
Next
For Each Counter As Integer In SheetIds.OrderByDescending(Function(i As Integer) i)
            CType(bkWorkBook.Sheets(Counter), Excel.Worksheet).Delete()
Next

By the way, I used the first, much simpler, method.

Leave a comment

Using Sum operator in LINQ

I needed to populate a list of record with file names along with how large the files were and who owned the file. Then, I needed to find how much space a particular user was taking up on the shared drive. The user would then be tarred and feathered, but this was nothing my code was going to have to deal with.

So I have a class of three properties, though I’ve only included the two relevant ones. I also declare a List(Of Results) to store my wonderfully awesome data:

Public Class Results
    Private _fileSize As Int64
    Public Property FileSize() As Int64
        Get
            Return _fileSize
        End Get
        Set(ByVal value As Int64)
            _fileSize = value
        End Set
    End Property
    Private _userName As String
    Public Property UserName() As String
        Get
            Return _userName
        End Get
        Set(ByVal value As String)
            _userName = value
        End Set
    End Property
 ... Lots of other code omitted
End Class
Dim ResultsFile As List(Of Results)

The details of how I populate the ResultsFile variable aren’t important, but here is the LINQ statement I use to total the file sizes:

Dim TotalFileSize As Int64 = Aggregate Result In ResultsFile Where Result.UserName = UserName Into Sum(Result.FileSize)

Simple and sweet.

Leave a comment