Reputation: 75
I have class as seen below
public class Channels
{
internal string CallerExt { get; set; }
internal string ChannelName { get; set; }
internal string CalleeExt { get; set; }
public Channels(string CallerExt, string ChannelName, string CalleeExt)
{
this.CallerExt = CallerExt;
this.ChannelName = ChannelName;
this.CalleeExt = CalleeExt;
}
}
I want to add the list of Channel objects if there all the values are new, if CallerExt
, and CaleeExt
already exist in the same object then ChannelName
should be updated with the new value for the same object?
I managed to find the object which contains CallerExt
& CalleeExt
Values matches with new values as seen below:
public static List<Channels> activeChannels = new List<Channels>();
if (!string.IsNullOrWhiteSpace(caller) && !string.IsNullOrWhiteSpace(now) && !string.IsNullOrWhiteSpace(callee))
{
var recentChannel = activeChannels.FirstOrDefault(c => c.CallerExt == caller && c.CalleeExt == callee);
}
But I am not sure how to update that specific Object with the new Channel Name? Thanks for your help in advance..
Upvotes: 0
Views: 1327
Reputation: 75
Thanks for those who tried to answer my question following solution worked for me
if (!string.IsNullOrWhiteSpace(caller) && !string.IsNullOrWhiteSpace(now) && !string.IsNullOrWhiteSpace(callee))
{
var recentChannel = activeChannels.FirstOrDefault(c => c.CallerExt == caller && c.CalleeExt == callee);
if (recentChannel != null)
recentChannel.ChannelName = now;
}
Upvotes: 0
Reputation: 14198
You can try this way, live demo here
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var listOfChanels = new List<Channels>{ new Channels("1", "1", "1")};
UpdateOrAdd(listOfChanels, new Channels("1", "2", "1"));
UpdateOrAdd(listOfChanels, new Channels("2", "2", "2"));
UpdateOrAdd(listOfChanels, new Channels("2", "3", "3"));
foreach(var item in listOfChanels)
Console.WriteLine(item.CalleeExt + item.CallerExt + item.ChannelName);
}
private static void UpdateOrAdd(List<Channels> list, Channels newObject)
{
var item = list.FirstOrDefault(p => p.CalleeExt == newObject.CalleeExt && p.CallerExt == newObject.CallerExt);
if(item == null){
list.Add(newObject);
}else{
item.ChannelName = newObject.ChannelName;
}
}
public class Channels
{
internal string CallerExt { get; set; }
internal string ChannelName { get; set; }
internal string CalleeExt { get; set; }
public Channels(string CallerExt, string ChannelName, string CalleeExt)
{
this.CallerExt = CallerExt;
this.ChannelName = ChannelName;
this.CalleeExt = CalleeExt;
}
}
}
Upvotes: 1