Thomas's profileBlogsBlogLists Tools Help

Blog


    03 March

    Intersection with Linq2SQL

     
    Imagine you have a data table that is specified as followed:
     
     
    CREATE TABLE MyTable
      ArticleId int NOT NULL,
      CategoryId int NOT NULL
     
     
    and you want to return all article ids that interesect with an array of Category Id's using LINQ2SQL.
     
    Here is a solution:
     
    int[] categoryIds = new int[] {29,5201,4};
    IQueryable<ObjectNodeView> result = context.MyTable;

    // make a select for the first category:
    int firstCategory = categoryIds.First();
    result = from a in result where a.CategoryId == firstCategory select a;

    // now intersect all other categories using a inner join:
    foreach(int categoryId in categoryIds.Skip(1))
    {
       result = from a in result
          join a2 in context.MyTable on a.ArticleId equals a2.ArticleId 
         where a2.CategoryId == categoryId
         select a;
    }

    Comments

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Trackbacks

    The trackback URL for this entry is:
    http://thomasgerber.spaces.live.com/blog/cns!58B30559C82E269C!680.trak
    Weblogs that reference this entry
    • None