开发者

Joining 2 Lists with LINQ?

I'm not sure on the best way to go about this one. Simply LINQ queries are easy enough for me, but I am looking for the most efficient way here.

I have 2 tables, Sliders and SliderItems. SliderItems have a FK that points to the Sliders Id.

I have been getting information on a particular slider like this:

    public static List<Slider> GetSlider(Slider sItem)
    {
        DBContext db = new DBContext();

        if (sItem.Id != Guid.Empty)
        {
            var list = from tbl in db.Sliders
                       where tbl.Id == sItem.Id
                       orderby tbl.Id
                       select tbl;

            return list.ToList();
        }
    }

So what I need to do for my home page is pull back a set of data that I want to stuff into a data list. Thereby combining the Slider + SliderItems that go along with it.

Do I just do a normal LINQ query with a JOIN statement and toss them into a generic list that goes back to my DataList?

Appreciate any thoughts and d开发者_运维技巧irection.


If your database already has the foreign key relationship between Sliders and SliderItems in place AND if your LINQ-to-SQL model includes both Sliders and SliderItems, then searching for a Slider automatically retrieves all related SliderItems:

public static IEnumerable<SliderItems> GetSliderItems(Guid sliderId)
{
    using (DataContext dc = new DataContext())
    {
        Slider result = dc.Sliders.Single(s => s.Id == sliderId);

        return result.SliderItems;
    }
}


That seems OK, but you've tagged your question as ASP.Net. My question to you is how large is this list and how often are you displaying this page?

If you are displaying it often and it isn't too large, I'd pull the slider table into memory and then run your query without hitting the DB.

In fact if possible you would cache the entire slider and slideritems if you can.

Even if you cache the most recently used if it makes sense to your app, not having to hit the DB will give you a better perf increase than optimising what appears to be a very trivial parent / child relationship. I assume you have an index in the database down tbl.Id?


I suggest you can use Linq query with join and put the data into the list. It works well for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜