簡體   English   中英

從類型注釋列表中獲得獨特的價值

[英]getting distinct value from a list of type comment

    List<Comment> StreamItemComments = objStreamItem.GetComments();

...

    foreach (Comment Item in StreamItemComments)
        {
            if (ClientUser.UserName != Item.Sender)
            {
                Notification notificationObj = new Notification
                {
                    Sender = ClientUser.UserName,
                    Recipient = Item.Sender,
                    Value = "whatever value here",
                    TrackBack = "",
                    IsRead = false
                };
                notificationObj.Add();
            }
        }

如果Item.Sender中的列表中有兩個“用戶名”,該怎么辦。 我想向用戶發送一次通知。 在這里,如果用戶名重復,它將發送兩個通知,因為我沒有從StreamItemComments中的列表中過濾出重復的Item.Senders。

考慮編寫查詢以說明您的意圖。 您希望項目注釋的不同發件人,但僅在發件人不是客戶用戶的情況下。 聽起來像查詢,不是嗎?

var recipients = StreamItemComments
                    .Where(item => item.Sender != ClientUser.UserName)
                    .Select(item => item.Sender)
                    .Distinct();

然后,您可以使用此查詢來構建通知

foreach (var item in recipients)
{
    var notificationObj = new Notification
    {
         Sender = ClientUser.UserName,
         Recipient = item,
         ...
    }

    notificationObj.Add();
}

您也可以將此對象構造也適合查詢,但是通過對每個對象的.Add()調用,我將其排除在查詢之外。 合並起來並不難,盡管您仍然需要遍歷輸出並為每個結果調用.Add()

您可以使用HashSet來確定是否已經處理了用戶名。

var set = new HashSet<string>();

foreach (var item in collection)
{
    if (set.Contains(item))
        continue;

    set.Add(item);

    // your notification code
}

對於您的具體問題, set將包含用戶名( Item.Sender )。 因此,您可能需要更改Add()參數。

使用.Distinct() 由於您無法使用默認比較器,因此可以實現這樣的比較器

class MyEqualityComparer : IEqualityComparer<Comment>
{
    public bool Equals(Comment x, Comment y)
    {
        return x.Sender.Equals(y.Sender);
    }

    public int GetHashCode(Comment obj)
    {
        return obj.Sender.GetHashCode();
    }
}

然后像這樣過濾它們。 您不需要if語句。

List<Comment> StreamItemComments = objStreamItem.GetComments()
    .Distinct(new MyEqualityComparer())
    .Where(x => x.Sender != ClientUser.UserName)
    .ToList();

你可以做的是

foreach ( Comment item in StreamItemComments)

將每個通知添加到Dictionary<user,msg>

然后在Dictionary之后的循環中使用另一個foreach key將實際消息發送給用戶。 這樣可以確保每位用戶僅發送一條消息

暫無
暫無

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

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