首页 > 代码库 > LINQ使用

LINQ使用

基于扩展方法和lamda表达式

1. 查询序列中满足一定条件 Where扩展方法

public interface ISlotPortBinding    {        byte SlotNumber { get; set; }        string PortName { get; set; }     }
private List<ISlotPortBinding> _slotPortBindings;
var firstBinding = _slotPortBindings.Where(x => x.SlotNumber <= 4).ToList();

2.序列属性赋值ForEach扩展方法

firstBinding.ForEach(x => x.PortName = “name”); 

 部分代码参考:

public void RefreshPortNames(string slot14Port, string slot58Port)        {            var firstBinding = _slotPortBindings.Where(x => x.SlotNumber <= 4).ToList();            var secondBinding = _slotPortBindings.Where(x => x.SlotNumber >= 4).ToList();            var slotPortBinding = firstBinding.FirstOrDefault();            bool isFirstBindingChanged = slotPortBinding != null && slotPortBinding.PortName != slot14Port;                        var firstOrDefault = secondBinding.FirstOrDefault();            bool isSecondBindingChanged = firstOrDefault != null && firstOrDefault.PortName != slot58Port;            if (isFirstBindingChanged)            {                firstBinding.ForEach(x => x.PortName = slot14Port);             }            if (isSecondBindingChanged)            {                secondBinding.ForEach(x => x.PortName = slot58Port);            }            if (isFirstBindingChanged || isSecondBindingChanged)            {                SlotNumberChangedEvent?.Invoke(_currentSlotPortBinding);            }            //刷新页面        }

 

LINQ使用