C# IList,List,IEnumber用法

c#删除 list中的元素和怎么去除空元素 https://www.cnblogs.com/shy1766IT/p/5186363.html

   for (int i = list.Count - 1; i >= 0; i--)
{
  if (list[i].NO == item.NO)
  {
  list.RemoveAt(i);
  }
}
 public void RemoveItemFromList(ref List <A> list, A item)
        {
            List <A> tempList = new List <A>();
            foreach (A a in list)
            {
                if (a.NO != item.NO && !tempList.Contains(a))
                    tempList.Add(a);
            }
            list = tempList;
        }
如果支除空元素,可以使用Split参数StringSplitOptions.RemoveEmptyEntries去实现

用法:
 string test = "程$晓$";
  使用:string[] temp = test.Split(new string[] { "$" }, StringSplitOptions.RemoveEmptyEntries);
  输出结果:数组长度为2 temp[0]="程" temp[1]="晓";
 

  使用:string[] temp = test.Split(new string[] { "$" }, StringSplitOptions.None);或string[] temp = test.Split('$');


  输出结果:数组长度为3 temp[0]="程" temp[1]="晓" temp[2]="";
  
string[] inputpids = productIds.IndexOf(',') > 0 ? productIds.Split(',').Distinct().ToArray() : new string[] { productIds };
int[] outputpids = Array.ConvertAll<string, int>(inputpids, delegate(string s)
{
var val = 0;
int.TryParse(s, out val);
return val;
});
req.ProductIds = outputpids.Where(c=>c>0).ToList();

C# List集合分组去重并保留最新的数据

class Program
    {
        static void Main(string[] args)
        {
            List<Person> list = new List<Person>
            {
                new Person
                {
                    id = 1,
                    name = "李小龙",
                    date = "2021-10-21"
                },
                 new Person
                {
                    id = 1,
                    name = "李小龙",
                    date = "2021-11-21"
                },
                  new Person
                {
                    id = 2,
                    name = "李世超",
                    date = "2021-10-21"
                }
            };
            //分组去重保留最新数据
            List<Person> newList = list.GroupBy(P => P.id).Select(P => P.OrderByDescending(P => P.date).First()).ToList();

            foreach (var item in newList)
            {
                Console.WriteLine($"人员编号:{item.id} 人员名称:{item.name} 日期:{item.date}");
            }
            Console.ReadKey();
        }

        public class Person
        {
            /// <summary>
            /// 人员编号
            /// </summary>
            public int id { get; set; }

            /// <summary>
            /// 人员名称
            /// </summary>
            public string name { get; set; }

            /// <summary>
            /// 日期
            /// </summary>
            public string date { get; set; }
        }
    }
posted @ 2022-03-03 11:14  朕在coding  阅读(275)  评论(0编辑  收藏  举报