开发者

LINQ to get the field values seperated by delimiter

I have a situation where I need to display ItemID and ItemName from Items table. Let's say ItemID is 002, and ItemName is Apple. I have another field called SupplementaryItems in the table which stores related ItemID seperated by | (delimiter), something like 003|004|005. I am using MVC3 with a repository pattern, something like

var items = _dataContext.items.AsQueryable();
items = from i in items 
          where i.Item_ID.equals(itemId)
           select i;

The above query with an itemId 002 will return Apple which works fine. Now, I also need to display all the supplementaryItems with their corresponding ItemName which means I need to split the supplementaryItem into array and use something like supplementaryItemArray contains itemID. But in this case, I need two separate calls to database, first one will return only item with itemID where I store the supplementaryItemID in a variable.

 var supplementMaterialsArr = supplementMaterials.ToString().Split('|');

and second one will return all the items, and I will loop through the second one to get the ItemName from the ItemID. FYI, this approach requires two separate calls to be made from controller, something like

var itemInformationAll = _repository.GetAllItems();
var itemInformation = _repository.GetItemDetailInformation(id); 

I think this is not so efficient approach. Anybody has better solution to this? Should I use LINQ self join? But if I use self join, will I able to get the supplemetaryItem with their corresponding ItemName with a single query? Any suggestions would be high开发者_开发知识库ly appreciated.


This is the best I could come up with. It will result in two queries, but never pulls the entire table into memory.

var q = from item in
        (from item in TblItems
        where item.ItemID == 1
        select new
        {
            Name = item.ItemName,
            SupplementaryItems = item.SupplementaryItems.Split('|')
        }).AsEnumerable()
        select new
        {
            Name = item.Name,
            SupplementaryItems = TblItems.Where (x => 
                item.SupplementaryItems.Select(y => int.Parse(y))
                .Contains(x.ItemID))
        };

I would however recommend to change the DB structure ta have a seperate table for the referencing items.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜