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();
}
}
What if there are two 'username' in List in Item.Sender. I'd like to send a notification once to the user. Here if there are duplicate usernames it will send two notifications because i am not filtering out duplicate Item.Senders from the list in StreamItemComments.
Consider writing a query to state your intentions. You want the distinct senders of the item comments, but only where the sender is not the client user. Sounds like a query, does it not?
var recipients = StreamItemComments
.Where(item => item.Sender != ClientUser.UserName)
.Select(item => item.Sender)
.Distinct();
You can then use this query to build your notifications
foreach (var item in recipients)
{
var notificationObj = new Notification
{
Sender = ClientUser.UserName,
Recipient = item,
...
}
notificationObj.Add();
}
You could also fit this object construction into the query, as well, but with your .Add()
invocation on each object, I left it out of the query. It wouldn't be difficult to incorporate, although you'd still need to loop over the output and invoke .Add()
for each result.
You can use a HashSet
to determine if you already handled a username.
var set = new HashSet<string>();
foreach (var item in collection)
{
if (set.Contains(item))
continue;
set.Add(item);
// your notification code
}
For your concrete problem, set
would contain usernames ( Item.Sender
). So you may want to change the Add()
argument.
Use .Distinct()
. Since you can't use the default comparer, you can implement one like this
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();
}
}
And then just filter them like this. You don't need the if
statement.
List<Comment> StreamItemComments = objStreamItem.GetComments()
.Distinct(new MyEqualityComparer())
.Where(x => x.Sender != ClientUser.UserName)
.ToList();
What you can do is in the
foreach ( Comment item in StreamItemComments)
add every notification to a Dictionary<user,msg>
and have another foreach key
in Dictionary afterwards loop to send the actual message to user. This will ensure that only one message per user is sent out
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.