本文整理汇总了C#中Common.List.Where方法的典型用法代码示例。如果您正苦于以下问题:C# List.Where方法的具体用法?C# List.Where怎么用?C# List.Where使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Common.List
的用法示例。
在下文中一共展示了List.Where方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LogisticMap
public LogisticMap(double mu, double r0, double rmax, double dr)
{
mapData.ChartType = SeriesChartType.Point ;
mapData.MarkerSize = 1;
mapData.MarkerColor = Color.Black;
int numberOfThreadsInMap =1 ;
List<double> activeThreadValues;
double eps = .005;
for(double r = r0; r < rmax; r+= dr ){
activeThreadValues = new List<double>();
Func<double, double> log = i => r * i * (1 - Math.Pow(i, mu));
for (int i = 150; i < 260; i++) {
var A = new Sequence(log, .2).GetElementAt(i);
if (A > double.MaxValue || A < double.MinValue) {
break;
}
if (activeThreadValues.Where(j => j < A + eps && j > A - eps).Count() == 0)
activeThreadValues.Add(A);
mapData.Points.AddXY(r, A);
}
if (activeThreadValues.Count > numberOfThreadsInMap) {
Console.WriteLine("Bifurcation point: " + r.ToString() + " " + activeThreadValues.Count.ToString() + " threads.");
numberOfThreadsInMap = activeThreadValues.Count();
eps /= numberOfThreadsInMap;
}
}
}
示例2: Main
static void Main(string[] args)
{
int totalCount = 3;
List<Student> listStudent = new List<Student>();
for (int i = 0; i < 3; i++)
{
Student objStudent = new Student();
Console.Write("Please enter the Student ID: ");
objStudent.StudentId = Int32.Parse(Console.ReadLine());
Console.Write("Please enter the Student Name: ");
objStudent.Name = Console.ReadLine();
listStudent.Add(objStudent);
}
//Query to get by name - only first occurence
//Student student = listStudent.First(x => x.Name == "Karthik");
Student student = listStudent.FirstOrDefault(x => x.Name == "Karthik");
if(student != null)
Console.WriteLine(string.Format("ID: {0} Name: {1}", student.StudentId, student.Name));
//Query to get by name - all occurences
//IEnumerable<Student> stdList = listStudent.Where(x => x.Name == "Karthik");
IEnumerable<Student> stdList = listStudent.Where(x => x.StudentId >= 20);
foreach (var student1 in stdList)
{
Console.WriteLine(string.Format("ID: {0} Name: {1}", student1.StudentId, student1.Name));
}
listStudent.Sort((std1, std2) => std1.Name.CompareTo(std2.Name));
listStudent.ForEach(x=>Console.WriteLine(x.Name));
}
示例3: MergeItems
private List<CalendarItem> MergeItems(List<CalendarItem> newItems, List<CalendarItem> fromRepo)
{
var result = new List<CalendarItem>();
var newModels = newItems.Except(fromRepo, new CalendarItemEqualityComparer()).ToList();
var updatet = fromRepo.Except(newModels,new CalendarItemEqualityComparer()).ToList();
updatet.ForEach(x =>
{
var model = newItems.FirstOrDefault(y => y.Id == x.Id);
if (model != null)
{
model.SyncStatus.CalenadCalendarItemStatus = IsModified(model, x)
? CalendarItemStatus.Updated
: CalendarItemStatus.Unmodified;
result.Add(model);
}
});
var deleted = fromRepo.Where(x => x.Start.Date >= DateTime.Now.Date).Except(newItems).Except(updatet);
newModels.ForEach(x => x.SyncStatus.CalenadCalendarItemStatus = CalendarItemStatus.New);
deleted.ForEach(x =>
{
x.SyncStatus.CalenadCalendarItemStatus = CalendarItemStatus.Deleted;
result.Add(x);
});
result.AddRange(newModels);
return result.OrderBy(x => x.Start).ToList();
}
示例4: LambdaExpression
private static void LambdaExpression(List<Student> students)
{
List<Student> selectedStudents = students.Where(s => s.GroupNumber == 2)
.OrderBy(s => s.FirstName)
.ToList();
selectedStudents.ForEach(s => Console.WriteLine("First name: {0}, Group number: {1}", s.FirstName, s.GroupNumber));
}
示例5: GetMadness
/// <summary>Returns numeric indicator of market activity. Higher value means higher activity (i.e. lot of trades with higher volume).</summary>
/// <param name="tradeHistory">Description of last executed trades of exchange</param>
/// <param name="now">Current local time of the exchange</param>
/// <returns>Coeficient in [0.0, 1.0] where 0.0 means totally peacefull market, 1.0 is wild.</returns>
internal static float GetMadness(List<Trade> tradeHistory, DateTime now)
{
//Trades of past 4mins
List<Trade> trades = tradeHistory.Where(trade => trade.Time >= now.AddSeconds(-240)).ToList();
if (!trades.Any())
{
return 0.0f;
}
//Group by time, so that single trade with big volume doesn't look like many trades
var groupped = new Dictionary<string, Trade>();
foreach (var trade in trades)
{
var key = trade.timestamp + "_" + trade.type;
if (!groupped.ContainsKey(key))
{
groupped.Add(key, new Trade(trade.price, trade.amount, trade.Type));
}
else
{
groupped[key].amount += trade.amount;
if (TradeType.BUY == trade.Type && trade.amount > groupped[key].amount)
groupped[key].amount = trade.amount;
else if (TradeType.SELL == trade.Type && trade.amount < groupped[key].amount)
groupped[key].amount = trade.amount;
}
}
// Console.WriteLine("DEBUG: {0} trades in past 90sec, {1} groupped by time", tradeHistory.Count, groupped.Count);
const int MIN_TRADES = 4;
const int MAX_TRADES = 14;
float intenseCoef;
if (groupped.Count < MIN_TRADES) //Too few trades
intenseCoef = 0.0f;
else if (groupped.Count >= MAX_TRADES) //Too many trades
intenseCoef = 1.0f;
else
intenseCoef = (float)(groupped.Count - MIN_TRADES) / (MAX_TRADES - MIN_TRADES);
const double MIN_AVG_VOLUME = 20;
const double MAX_AVG_VOLUME = 50;
float volumeCoef;
double avgVolume = groupped.Sum(trade => trade.Value.amount) / groupped.Count;
// Console.WriteLine("DEBUG: avgVolume={0}", avgVolume);
if (avgVolume < MIN_AVG_VOLUME)
volumeCoef = 0.0f;
else if (avgVolume >= MAX_AVG_VOLUME)
volumeCoef = 1.0f;
else
volumeCoef = (float)((avgVolume - MIN_AVG_VOLUME) / (MAX_AVG_VOLUME - MIN_AVG_VOLUME));
// Console.WriteLine("DEBUG: intensityCoef={0}, volumeCoef={1}", intenseCoef, volumeCoef);
//Average of volume and frequency coeficients
return (intenseCoef + volumeCoef) / 2;
}
示例6: Expression
private static void Expression(List<Student> students)
{
var selectedStudents = students.Where(s => s.Group.DepartmentName.Equals("Mathematics"))
.ToList();
foreach (var student in selectedStudents)
{
Console.WriteLine("Name: {0}, Department: {1}", student.FirstName + " " + student.LastName, student.Group.DepartmentName);
}
}
示例7: Expression
private static void Expression(List<Student> students)
{
var selectedStudents = students.Where(s => s.Marks.Count > 0 && s.Marks.Contains(6))
.Select(s => new
{
FullName = s.FirstName + " " + s.LastName,
Marks = s.MarksPrint()
});
foreach (var student in selectedStudents)
{
Console.WriteLine("{0} {1}", student.FullName, student.Marks);
}
}
示例8: Main
private static void Main()
{
List<Student> list = new List<Student>();
for (int i = 0; i < 20; i++)
{
Student student = new Student(GenerateRandom.Text(10), GenerateRandom.Text(10));
student.Age = GenerateRandom.Number(15, 35);
list.Add(student);
}
Console.WriteLine("\nAll:\n");
list.ForEach(x => Console.WriteLine(x));
Console.WriteLine("\nFilterd 1:\n");
var sorted1 = list.Where(x => x.Age >= 18 && x.Age <= 24)
.Select(x => new
{
FirstName = x.FirstName,
LastName = x.LastName,
Age = x.Age
}).ToList();
sorted1.ForEach(x => Console.WriteLine(x.FirstName + " " + x.LastName + " " + x.Age));
Console.WriteLine("\nFilterd 2:\n");
var sorted2 = from s in list
where s.Age >= 18 && s.Age <= 24
select new
{
FirstName = s.FirstName,
LastName = s.LastName,
Age = s.Age
};
foreach (var x in sorted2)
{
Console.WriteLine(x.FirstName + " " + x.LastName + " " + x.Age);
}
}
示例9: Expression
private static void Expression(List<Student> students)
{
var selectedStudents = students.Where(s => s.Fn.ToString().Substring(s.Fn.ToString().Length - 2, 2) == "06")
.Select(s => new
{
Fn = s.Fn,
Marks = s.Marks
});
foreach (var student in selectedStudents)
{
Console.Write(student.Fn + ": ");
foreach (var mark in student.Marks)
{
Console.Write("{0} ", mark);
}
Console.WriteLine();
}
}
示例10: AggregateInternal
private WeatherInfo AggregateInternal(List<WeatherInfo> weatherInfos)
{
var weatherInfo = new WeatherInfo();
var existingWeatherInfos = weatherInfos.Where(p => p != null).ToList();
weatherInfo.Country = existingWeatherInfos.GetOneResult(info => info.Country != null, info => info.Country);
weatherInfo.Description = existingWeatherInfos.GetOneResult(info => info.Description != null, info => info.Description);
weatherInfo.Elevation = existingWeatherInfos.GetOneResult(info => info.Elevation != null, info => info.Elevation);
weatherInfo.RelativeHumidity = existingWeatherInfos.GetOneResult(info => info.RelativeHumidity != null, info => info.RelativeHumidity);
weatherInfo.WindDirection = existingWeatherInfos.GetOneResult(info => info.WindDirection != null, info => info.WindDirection);
var latititudes = existingWeatherInfos.GetMultipleResults(p => p.Latitude.HasValue, p => p.Latitude);
weatherInfo.Latitude = latititudes.Any() ? latititudes.Average() : null;
var longitudes = existingWeatherInfos.GetMultipleResults(p => p.Longitude.HasValue, p => p.Longitude);
weatherInfo.Longitude = longitudes.Any() ? longitudes.Average() : null;
var pressuresInMb = existingWeatherInfos.GetMultipleResults(p => p.PressureMb.HasValue, p => p.PressureMb);
weatherInfo.PressureMb = pressuresInMb.Any() ? MathExtensions.Floor(pressuresInMb.Average()) : null;
var temperaturesCelcius = existingWeatherInfos.GetMultipleResults(p => p.TemperatureCelcius.HasValue, p => p.TemperatureCelcius);
weatherInfo.TemperatureCelcius = temperaturesCelcius.Any() ? temperaturesCelcius.Average() : null;
var visibilityDistances = existingWeatherInfos.GetMultipleResults(p => p.VisibilityDistance.HasValue, p => p.VisibilityDistance);
weatherInfo.VisibilityDistance = visibilityDistances.Any() ? visibilityDistances.Average() : null;
var windAngles = existingWeatherInfos.GetMultipleResults(p => p.WindAngle.HasValue, p => p.WindAngle);
weatherInfo.WindAngle = windAngles.Any() ? MathExtensions.Floor(windAngles.Average()) : null;
var windSpeedsKph = existingWeatherInfos.GetMultipleResults(p => p.WindSpeedKph.HasValue, p => p.WindSpeedKph);
weatherInfo.WindSpeedKph = windSpeedsKph.Any() ? windSpeedsKph.Average() : null;
var windSpeedsMs = existingWeatherInfos.GetMultipleResults(p => p.WindSpeedMs.HasValue, p => p.WindSpeedMs);
weatherInfo.WindSpeedMs = windSpeedsMs.Any() ? windSpeedsMs.Average() : null;
return weatherInfo;
}
示例11: cosumeRecordAnalysis
/// <summary>
/// 消费数据分析
/// </summary>
/// <returns></returns>
bool cosumeRecordAnalysis()
{
this._IsRunning = true;
bool res = true;
try
{
bool canStart = false;
TimeSpan tsNow = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
foreach (TimeSpan item in this._ListCollectSpan)
{
TimeSpan tsEnd = new TimeSpan();
if (item.Hours == 23)
{
tsEnd = new TimeSpan(23, 59, 59);
}
else
{
tsEnd = new TimeSpan(item.Hours + 1, item.Minutes, 0);
}
if (tsNow > item && tsNow < tsEnd)
{
canStart = true;
break;
}
}
if (!canStart)
{
this._IsRunning = false;
return false;
}
//消费机最后同步时间
DateTime dtMacSync = DateTime.MinValue;
//找出消费机主档信息,检查是否全部收数完毕,是则进行平数处理,否则不操作
#region 找出消费机主档信息,检查是否全部收数完毕,是则进行平数处理,否则不操作
List<ConsumeMachineMaster_cmm_Info> listMachineInfos = this._IConsumeMachineBL.SearchRecords(new ConsumeMachineMaster_cmm_Info()
{
cmm_cStatus = Common.DefineConstantValue.ConsumeMachineStatus.Using.ToString(),
});
if (listMachineInfos == null)
{
this._IsRunning = false;
return false;
}
else
{
if (listMachineInfos != null && listMachineInfos.Count > 0)
{
if (listMachineInfos != null && listMachineInfos.Count > 0)
{
dtMacSync = listMachineInfos[0].cmm_dLastAccessTime;
}
}
List<ConsumeMachineMaster_cmm_Info> listUnSyncMachineInfos = listMachineInfos.Where(x =>
x.cmm_dLastAccessTime.Hour != dtMacSync.Hour).ToList();
if (listUnSyncMachineInfos != null && listUnSyncMachineInfos.Count > 0)
{
this._IsRunning = false;
return false;
}
List<ConsumeMachineMaster_cmm_Info> listUnConnMachineInfos = listMachineInfos.Where(x =>
x.cmm_lIsActive == true
&& x.cmm_lLastAccessRes == false
).ToList();
if (listUnConnMachineInfos == null || (listUnConnMachineInfos != null && listUnConnMachineInfos.Count > 0))
{
this._IsRunning = false;
return false;
}
}
#endregion
//就餐时段
#region 学生真实就餐时段列表
List<CodeMaster_cmt_Info> listMealTimeSpan = this._ICodeMasterBL.SearchRecords(new CodeMaster_cmt_Info()
{
cmt_cKey1 = Common.DefineConstantValue.CodeMasterDefine.KEY1_MealTimeSpan
});
if (listMealTimeSpan == null || (listMealTimeSpan != null && listMealTimeSpan.Count < 1))
{
this._IsRunning = false;
return false;
}
#endregion
//定餐时段
#region 学生定餐设置生成时间列表
List<CodeMaster_cmt_Info> listBookingMealTimeSpan = this._ICodeMasterBL.SearchRecords(new CodeMaster_cmt_Info()
{
cmt_cKey1 = Common.DefineConstantValue.CodeMasterDefine.KEY1_BWListUploadInterval
//.........这里部分代码省略.........
示例12: ShowSubForm
/// <summary>
/// 显示子窗体
/// </summary>
/// <param name="sender">发送显示请求的按钮或其他控件</param>
/// <param name="dpnlContainer">显示容器</param>
/// <param name="strTabName">卡位位置</param>
/// <param name="strTabName">显示卡位位置</param>
public void ShowSubForm(object sender, DockPanel dpnlContainer, string strTabName, DockState state)
{
string strFormName = string.Empty;
MenuItem itemMenu = sender as MenuItem;
if (itemMenu != null)
{
strFormName = (itemMenu.Tag as Sys_FormMaster_fom_Info).fom_cExePath;
}
else
{
ToolStripButton itemBtn = sender as ToolStripButton;
if (itemBtn != null)
{
strFormName = (itemBtn.Tag as Sys_FormMaster_fom_Info).fom_cExePath;
}
}
if (!string.IsNullOrEmpty(strFormName))
{
if (!string.IsNullOrEmpty(strFormName))
{
BaseForm frmTarget = GetFormIn(strFormName);
frmTarget.EditState = this.EditState;
frmTarget.BaseParam = this.BaseParam;
frmTarget.UserInformation = this.UserInformation;
if (!string.IsNullOrEmpty(strTabName))
{
frmTarget.TabText = strTabName;
}
if (frmTarget == null)
{
ShowErrorMessage("生成子窗体异常,请联系管理员。");
}
else
{
//var tmpList = dpnlContainer.Contents.Where(x => x.DockHandler.TabText == frmTarget.TabText).ToList();
var tmpList = dpnlContainer.Contents.Where(x => x.DockHandler.Form.Name == frmTarget.Name).ToList();
if (tmpList != null && tmpList.Count < 1)
{
frmTarget.BaseDockPanel = dpnlContainer;
frmTarget.Show(dpnlContainer, state);
}
else if (tmpList != null && tmpList.Count > 0)//當使用相同窗體不同編輯模式時,Form相同,需要外加編輯狀態屬性判斷是否已被打開該窗體
{
List<BaseForm> listCompForm = new List<BaseForm>();
foreach (var panItem in tmpList)
{
BaseForm bsTarget = panItem.DockHandler.Form as BaseForm;
if (bsTarget != null)
{
listCompForm.Add(bsTarget);
}
}
var listTmp = listCompForm.Where(x => x.EditState == this.EditState).ToList();
if (listTmp != null && listTmp.Count < 1)
{
frmTarget.BaseDockPanel = dpnlContainer;
frmTarget.Show(dpnlContainer, state);
}
else if (listTmp != null && listTmp.Count > 0)
{
listTmp[0].DockHandler.Activate();
}
}
}
}
else
{
ShowErrorMessage("发送显示请求的对象没有携带窗口信息,请联系管理员。");
}
}
else
{
ShowErrorMessage("发送显示请求的对象有误,请联系管理员。");
}
}
示例13: GetCalendars
public static IEnumerable<ExigoService.Calendar> GetCalendars(GetCalendarsRequest request)
{
var context = Exigo.ODataCalendars();
var corporateCalendarContext = Exigo.OData();
var calendars = new List<Calendar>();
var cacheKey = "GetCalendars/{0}/{1}".FormatWith(request.CustomerID ?? 0, request.IncludeCalendarSubscriptions);
var cache = (HttpContext.Current != null) ? HttpContext.Current.Cache : null;
// Check the cache to see if we've already made this call recently
if (cache == null || cache[cacheKey] == null)
{
GlobalUtilities.RunAsyncTasks(
// Add the customer's personal calendars
() =>
{
if (request.CustomerID != null)
{
var apiCalendars = context.Calendars
.Where(c => c.CustomerID == (int)request.CustomerID)
.ToList();
foreach (var apiCalendar in apiCalendars)
{
calendars.Add((ExigoService.Calendar)apiCalendar);
}
}
},
// Include the customer's calendar subscriptions if applicable
() =>
{
if (request.CustomerID != null && request.IncludeCalendarSubscriptions)
{
var calendarSubscriptions = GetCustomerCalendarSubscriptions((int)request.CustomerID);
var calendarSubscriptionsIDs = calendarSubscriptions.Select(c => c.CalendarID).ToList();
if (calendarSubscriptionsIDs.Count > 0)
{
var apiCalendars = context.Calendars
.Where(calendarSubscriptionsIDs.ToOrExpression<CalendarContext.Calendar, Guid>("CalendarID"))
.ToList();
foreach (var apiCalendar in apiCalendars)
{
calendars.Add((ExigoService.Calendar)apiCalendar);
}
}
}
},
// Include any additional requested calendars
() =>
{
if (request.CalendarIDs != null && request.CalendarIDs.Count() > 0)
{
var apiCalendars = context.Calendars
.Where(request.CalendarIDs.ToList().ToOrExpression<CalendarContext.Calendar, Guid>("CalendarID"))
.ToList();
foreach (var apiCalendar in apiCalendars)
{
calendars.Add((ExigoService.Calendar)apiCalendar);
}
}
}
);
// If we asked for a specific customer's calendars, and none of the calendars belong to that customer, create a default calendar and add it to the collection.
if (request.CustomerID != null && calendars.Where(c => c.CustomerID == (int)request.CustomerID).Count() == 0)
{
var defaultCalendar = CreateDefaultCalendar((int)request.CustomerID);
calendars.Add(defaultCalendar);
}
if (cache != null)
{
cache.Insert(cacheKey, calendars,
null,
DateTime.Now.AddMinutes(5),
Cache.NoSlidingExpiration,
CacheItemPriority.Normal,
null);
}
}
else
{
calendars = (List<ExigoService.Calendar>)cache[cacheKey];
}
// Return the calendars
foreach (var calendar in calendars)
{
yield return calendar;
}
}
示例14: Expression
private static void Expression(List<Student> students)
{
List<Student> selectedStudents = students.Where(s => s.Tel.Substring(0, s.Tel.IndexOf('/')) == "02").ToList();
selectedStudents.ForEach(student => Console.WriteLine("{0} {1} {2}", student.FirstName, student.LastName, student.Tel));
}
示例15: BindcboMachineBigArea
//根據事業單位綁定區域
private void BindcboMachineBigArea(string description)
{
var allarea = MasterBLLFactory.GetBLL<IAreaMasterBL>(MasterBLLFactory.AreaMaster).SearchRecords(new AreaMaster_amr_Info());
List<AreaMaster_amr_Info> alldescription = new List<AreaMaster_amr_Info>();
foreach (AreaMaster_amr_Info item in allarea)
{
alldescription.Add(item);
}
alldescription = alldescription.Where(d => d.amr_cPublicInstitution.Trim().ToUpper() == description.ToUpper().Trim()).ToList();
cboMachineBigArea.DisplayMember = "amr_cAreaName";
cboMachineBigArea.ValueMember = "amr_cRecordID";
cboMachineBigArea.DataSource = alldescription;
cboMachineBigArea.SelectedIndex = -1;
}