展示效果图
代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 分割字符串 { class Program { static void Main(string[] args) { Studen st1 = new Studen { Id = 1, Name = "张三", Aihao = "打羽毛球,打乒乓球" }; Studen st2 = new Studen { Id = 2, Name = "李四", Aihao = "打篮球" }; Studen st3 = new Studen { Id = 3, Name = "王五", Aihao = "打台球,打羽毛球,踢足球" }; Studen st4 = new Studen { Id = 4, Name = "赵六", Aihao = "打羽毛球,打乒乓球,打游戏" }; Studen st5 = new Studen { Id = 5, Name = "孙七", Aihao = "打羽毛球" }; Studen st6 = new Studen { Id = 6, Name = "周八", Aihao = "下象棋" }; List<Studen> stList = new List<Studen>(); List<Studen> newStList = new List<Studen>(); stList.Add(st1); stList.Add(st2); stList.Add(st3); stList.Add(st4); stList.Add(st5); stList.Add(st6);
foreach (var item in stList) { if (item.Aihao.IndexOf(",") > 0) { string[] arr = item.Aihao.Split(','); foreach (string s in arr) { Studen st8 = new Studen(); st8.Id = item.Id; st8.Name = item.Name; st8.Aihao = s; newStList.Add(st8); } } else { Studen st7 = new Studen(); st7.Id = item.Id; st7.Name = item.Name; st7.Aihao = item.Aihao; newStList.Add(st7); } } Console.WriteLine("旧"); foreach (var item in stList) { Console.Write(item.Id + " "); Console.Write(item.Name + " "); Console.WriteLine(item.Aihao); } Console.WriteLine("新"); foreach (var item in newStList) { Console.Write(item.Id + " "); Console.Write(item.Name + " "); Console.WriteLine(item.Aihao); } Console.ReadKey(); } } public class Studen { private int id; private string name; private string aihao; public int Id { get => id; set => id = value; } public string Name { get => name; set => name = value; } public string Aihao { get => aihao; set => aihao = value; } } }