簡體   English   中英

如何比較清單 <long> 使用逗號分隔的ID(使用linq實體)

[英]How to compare a List<long> with a comma-separated ids, using linq to entities

我的用戶個人資料中有“興趣Ids列。 List<long> interest ids 我想使用實體框架在列表中獲取與興趣ID相匹配的用戶個人資料。

例如

  • 山姆1,5,9,13,4,8
  • 約翰2,7,13,9
  • 凱蒂1,4,8,12,15

清單:{4,8}

我想輸出為{Sam,Kettie}

更新: Db結構-

public class UserProfile
{    
    public long UserId { get; set; }
    public string FullName { get; set; }
    public string Interests { get; set; }  //Store comma separated Interest Ids here 
}

public class Interest
{
    public long InterestId { get; set; }
    public string Name { get; set; }
}

我通過實現

var interestIds = db.Interests.Where(i => i.Name.Contains(query))
        .Select(i=> i.InterestId)
        .ToList();
var profiles = new List<UserProfile>();
foreach (var id in interestIds)
{
    profiles.AddRange(db.UserProfiles
        .Where(p=> p.Interests.Contains(id.ToString()))
        .ToList());
}
return profiles;

但是,在處理大量記錄時,它需要很長時間才能執行,因此我需要幫助來優化此記錄。

抱歉,如果答案不完全是您要查找的內容,因為我不熟悉實體框架,而是純粹從C#的角度來看:

對於您的interestIds中的每個id,您每次都在過濾整個數據庫(並通過檢查每個條目上的集合來做到這一點)-我想您在這里會遭受性能損失。

如果可能,您可以將每個興趣ID映射到用戶名列表。 這僅需要執行一次,並且可能會表現更好-類似於:

var dict = new Dictionary<long, List<string>>();
foreach(var user in userProfiles)
{
    foreach(var interest in user.Interests)
    {
        List<string> names;
        if(dict.TryGetValue(interest, out names))
            names.Add(user.Name);
        else
            dict.Add(interest, new[] { user.Name }.ToList());
    }
}

long[] interestIds = new[] { 4, 8 };

HashSet<string> profiles = new HashSet<string>();
foreach (var interestId in interestIds)
    profiles.UnionWith(dict[interestId]);

因此,遍歷每個用戶的每個興趣,然后將每個興趣添加為鍵,並將用戶添加到該鍵的用戶列表中。

然后,您可以遍歷您的interestId列表,並將匹配列表中的用戶名從字典中拉出(請注意HashSet-這將使您獲得與多個興趣匹配的用戶的重復名稱)。

這將幫助您sql server only oncesql server only once執行sql server only once查詢..我使用事件profiler對其進行了檢查,它更好,因為當foreach loop iterate ..每次打開和關閉sql連接時..這導致大量填充您的期望結果慢點..

        var interestIds = db.Interests.Where(i => i.Name.Contains("interest_name"))
                        .Select(i => i.InterestId)
                        .ToList().ConvertAll(i => i.ToString());
        //var profiles = new List<UserProfile>();

        var allProfiles = (from UserProfile up in db.UserProfiles
                           from i in interestIds
                           where up.Interests.Contains(i)
                           select up).ToList();
        return allProfiles;

        //string sId = null;
        //foreach (var id in interestIds)
        //{
        //    sId = id.ToString();
        //    profiles.AddRange(db.UserProfiles
        //        .Where(p => p.Interests.Contains(sId))
        //        .ToList());
        //}
        //return profiles;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM