从类型注释列表中获取不同的值

时间:2011-12-28 03:35:48

标签: c# asp.net sql class distinct

    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中的List中有两个“用户名”,该怎么办?我想向用户发送一次通知。如果有重复的用户名,它将发送两个通知,因为我没有从StreamItemComments的列表中过滤掉重复的Item.Senders。

4 个答案:

答案 0 :(得分:3)

考虑编写一个查询来表明你的意图。您需要项目注释的不同发件人,但仅限于发件人不是客户端用户的情况。听起来像一个查询,不是吗?

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(),但要合并并不困难。

答案 1 :(得分:2)

您可以使用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()参数。

答案 2 :(得分:1)

使用.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();

答案 3 :(得分:0)

你可以做的是

foreach ( Comment item in StreamItemComments)

将每个通知添加到Dictionary<user,msg>

然后在 Dictionary 中有另一个foreach key,然后循环将实际消息发送给用户。这将确保每个用户只发送一条消息

相关问题