I have this logic that seems complicated checking the length and adding a colon. I'd like to see if any of you C# experts can help me simplify it. If the replace remove the full text then I am just adding the word Result. If it removes the make then I am just displaying the model.
Is there a way I can remove the if statement and combine into one?
namespace DupName
{
public class Program
{
static void Main(string[] args)
{
StringBuilder childName = new StringBuilder();
List<Item> items = new List<Item>()
.AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi A3 Premium Plus" })
.AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "Audi" })
.AddAlso(new Item { Id = 1, Name = "Audi", ChildName = "Audi" })
.AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S5 Premium Plus 3.0 TFSI quattro" })
.AddAlso(new Item { Id = 2, Name = "Audi", ChildName = "S3 Premium Plus 3.0 TFSI quattro" });
foreach (var item in items)
{
string temp = item.ChildName.Replace(item.Name, "").Trim();
if (temp.Length == 0)
{
Console.WriteLine(string.Format("{0}","Result"));
}else
{
Console.WriteLine(string.Format("{0}: {1} - {2}", "Result", temp, item.Name));
}
}
}
}
public static class Extensions
{
public static List<T> AddAlso<T>(this List<T> list, T item)
{
list.Add(item);
return list;
}
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string ChildName { get; set; }
}
Output
Result: A3 Premium Plus - Audi
Result
Result
Result: S5 Premium Plus 3.0 TFSI quattro - Audi
Result: S3 Premium Plus 3.0 TFSI quattro - Audi
temp.Length == 0
?what complications that you are experiencing ? and what do you want to achieve ? \$\endgroup\$