本文整理汇总了C#中System.Windows.Documents.List.Any方法的典型用法代码示例。如果您正苦于以下问题:C# List.Any方法的具体用法?C# List.Any怎么用?C# List.Any使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Windows.Documents.List
的用法示例。
在下文中一共展示了List.Any方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InitializePlugins
private void InitializePlugins()
{
var assemblies = GetAssemblies("Plugins");
List<MenuItem> menuItems = new List<MenuItem>();
foreach (var assembly in assemblies)
{
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.IsClass && type.IsPublic && type.GetInterface(typeof(IPlugin).FullName) != null)
{
var item = Activator.CreateInstance(type) as IPlugin;
var menuItem = item.GetMenuItem();
menuItem.Tag = item;
menuItem.Click += pluginMenuItem_Click;
menuItems.Add(menuItem);
}
}
}
if (menuItems.Any())
{
var tools = new MenuItem();
tools.Header = "Tools";
menuItems.ForEach((i) => { tools.Items.Add(i); });
v_Menu.Items.Add(tools);
}
}
示例2: GetWpAlbums
private void GetWpAlbums(object state)
{
List<ServiceAgnosticAlbum> albums = new List<ServiceAgnosticAlbum>();
IITPlaylist libraryPlaylist = GetLibraryPlaylist();
if (libraryPlaylist != null)
{
IITTrackCollection tracks = libraryPlaylist.Tracks;
int i = 1;
foreach (IITFileOrCDTrack track in tracks)
{
var artistName = track.Artist;
var albumName = track.Album;
if (!string.IsNullOrEmpty(artistName) &&
!string.IsNullOrEmpty(albumName) &&
!albums.Any(a => a.AlbumName == albumName && a.ArtistName == artistName))
{
albums.Add(new ServiceAgnosticAlbum(albumName, artistName));
}
i++;
}
}
App.AlbumsToImport = albums;
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() => this.Navigate(new CollectionImporter())));
}
示例3: GetWpAlbums
private void GetWpAlbums(object state)
{
var wmp = new WindowsMediaPlayer();
var collection = wmp.mediaCollection;
this.authorIndex = collection.getMediaAtom("Author");
this.albumArtistIndex = collection.getMediaAtom("WM/AlbumArtist");
this.albumIndex = collection.getMediaAtom("Album");
IWMPPlaylist allMedia = collection.getAll();
List<ServiceAgnosticAlbum> albums = new List<ServiceAgnosticAlbum>();
for (int i = 0; i < allMedia.count; i++)
{
var currentMedia = allMedia.get_Item(i);
var artistName = GetArtist(currentMedia);
var albumName = GetAlbum(currentMedia);
if (!string.IsNullOrEmpty(artistName) &&
!string.IsNullOrEmpty(albumName) &&
!albums.Any(a => a.AlbumName == albumName && a.ArtistName == artistName))
{
albums.Add(new ServiceAgnosticAlbum(albumName, artistName));
}
}
App.AlbumsToImport = albums;
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() => this.Navigate(new CollectionImporter())));
}
示例4: LaunchWindow
public LaunchWindow()
{
string gameConfigurationFolder = "GameConfiguration";
string gameConfigurationsPath = Path.Combine(gameConfigurationFolder, "gameConfigs.json");
InitializeComponent();
if (!Directory.Exists(gameConfigurationFolder))
Directory.CreateDirectory(gameConfigurationFolder);
//Loading the last used configurations for hammer
RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Hammer\General");
var configs = new List<GameConfiguration>();
//try loading json
if (File.Exists(gameConfigurationsPath))
{
string jsonLoadText = File.ReadAllText(gameConfigurationsPath);
configs.AddRange(JsonConvert.DeserializeObject<List<GameConfiguration>>(jsonLoadText));
}
//try loading from registry
if (rk != null)
{
string BinFolder = (string)rk.GetValue("Directory");
string gameData = Path.Combine(BinFolder, "GameConfig.txt");
configs.AddRange(GameConfigurationParser.Parse(gameData));
}
//finalise config loading
if (configs.Any())
{
//remove duplicates
configs = configs.GroupBy(g => g.Name).Select(grp => grp.First()).ToList();
//save
string jsonSaveText = JsonConvert.SerializeObject(configs, Formatting.Indented);
File.WriteAllText(gameConfigurationsPath, jsonSaveText);
if (configs.Count == 1)
Launch(configs.First());
GameGrid.ItemsSource = configs;
}
else//oh noes
{
LaunchButton.IsEnabled = false;
WarningLabel.Content = "No Hammer configurations found. Cannot launch.";
}
}
示例5: EditTestsWindow
public EditTestsWindow(List<TestCase> testCases)
{
TestCases = testCases;
InitializeComponent();
lstTestCases.Items.Clear();
foreach (var t in testCases)
{
lstTestCases.Items.Add(t);
}
if (testCases.Any())
{
lstTestCases.SelectedIndex = 0;
}
UpdateUI();
}
示例6: RemoveEntry
public void RemoveEntry(PhoneApplicationPage page, List<string> uris)
{
var lastPage = page.NavigationService.BackStack.FirstOrDefault();
if (lastPage != null)
{
for (int i = page.NavigationService.BackStack.Count() - 1; i >= 0; i--)
{
bool remove = uris.Any(x => { return page.NavigationService.BackStack.ElementAt(i).Source.ToString().Contains(x); });
if (remove)
page.NavigationService.RemoveBackEntry();
}
}
}
示例7: GroupToEdges
public IEnumerable<Edge> GroupToEdges(List<Point> points)
{
List<Edge> edges = new List<Edge>();
while (points.Any())
{
creatingTime.Start();
var point = points.First();
points.Remove(point);
var edge = new Edge(point);
creatingTime.Stop();
edges.Add(GrowEdge(edge, points));
}
return edges;
}
示例8: TwitterSampleStream
private void TwitterSampleStream()
{
ListWordsByFrequency frequencyList = new ListWordsByFrequency();
var logFile = System.IO.File.ReadAllLines(@"C:\Users\Daniel\Source\Repos\TwitterCrawl\positive-words.txt");
List <string> StringList = new List<string>(logFile);
Globals.Stream = Stream.CreateSampleStream();
int incomming = 0;
int success = 0;
Globals.Stream.TweetReceived += (sender, args) =>
{
Dispatcher.BeginInvoke(new Action(() =>
{
incomming++;
label.Content = incomming;
label1.Content = success;
string tweet = args.Tweet.ToString();
bool test = StringList.Any(tweet.Contains);
if (test)
{
success++;
txtBxTwitterFeed.Clear();
txtBxTwitterFeed.Text = tweet;
var matchingvalues = StringList.FindAll(tweet.Contains);
StringBuilder builder = new StringBuilder();
foreach (string v in matchingvalues) // Loop through all strings
{
builder.Append(v).Append(" "); // Append string to StringBuilder
}
frequencyList.split(builder.ToString());
rTxtBxFrequency.Document.Blocks.Clear();
rTxtBxFrequency.Document.Blocks.Add(new Paragraph(new Run(frequencyList.output)));
}
}));
};
}
示例9: PopulateLayoutRadioButtonsFromDisk
/// <summary>
/// Populates the layout radio buttons from disk.
/// </summary>
private void PopulateLayoutRadioButtonsFromDisk()
{
List<RadioButton> radioButtonList = new List<RadioButton>();
var rockConfig = RockConfig.Load();
List<string> filenameList = Directory.GetFiles( ".", "*.dplx" ).ToList();
foreach ( var fileName in filenameList )
{
DplxFile dplxFile = new DplxFile( fileName );
DocumentLayout documentLayout = new DocumentLayout( dplxFile );
RadioButton radLayout = new RadioButton();
if ( !string.IsNullOrWhiteSpace( documentLayout.Title ) )
{
radLayout.Content = documentLayout.Title.Trim();
}
else
{
radLayout.Content = fileName;
}
radLayout.Tag = fileName;
radLayout.IsChecked = rockConfig.LayoutFile == fileName;
radioButtonList.Add( radLayout );
}
if ( !radioButtonList.Any( a => a.IsChecked ?? false ) )
{
if ( radioButtonList.FirstOrDefault() != null )
{
radioButtonList.First().IsChecked = true;
}
}
lstLayouts.Items.Clear();
foreach ( var item in radioButtonList.OrderBy( a => a.Content ) )
{
lstLayouts.Items.Add( item );
}
}
示例10: ShowContainers
public FlowDocument ShowContainers(List<Container> containers, List<Vehicle> vehicles)
{
var doc = new FlowDocument();
foreach (var vehicle in vehicles)
{
var tempList = UnpackVehicle(vehicle);
AddMainHeader(doc,
"Список контейнеров для автомобиля " + vehicle.Name + "(" + tempList.Count() +
" контейнеров; общий вес груза " + vehicle.Mass + " кг.)");
AddTable(doc, tempList);
}
if (containers.Any())
{
AddMainHeader(doc,
"Список контейнеров не поместившихся в машины " + "(" + containers.Count() + " контейнеров)");
AddTable(doc, containers);
}
else
{
AddMainHeader(doc, "Все контейнеры загружены.");
}
return doc;
}
示例11: FillGridWithInfo
private void FillGridWithInfo()//Fetching info for each cell of Info grid and placing it there
{
int rows = WeekGrid.Rows;//we will need row and column number to properly placing info into the grid;
int columns = WeekGrid.Columns;
List<Group> searchresult = new List<Group>();
foreach (ListView listView in WeekGrid.Children)
{
int index = WeekGrid.Children.IndexOf(listView);
int row = index / columns;
int column = index % columns;
searchresult = groups.FindAll(delegate(Group group)//Looking up if there are ny group for at this date;
{
DateTime weekday = GetStartOfCurrentWeek().AddDays(column);
return group.Date == weekday;
});
if (!searchresult.Any())//If there are none - setting empty labels.
{
for (int i = 0; i < listView.Items.Count; i++)
{
((Label)listView.Items[i]).Content = " ";
((Label)listView.Items[i]).Tag = null;
((Label)listView.Items[i]).Background = Brushes.White;
}
}
else if (searchresult.Any())//If there are any - we narrow search further to timeperiod.
{
searchresult = searchresult.FindAll(delegate(Group gp)
{
timeperiod time = (timeperiod)row;
return gp.Time == time;
});
if (!searchresult.Any())//If there are none, we again set all to empty;
{
for (int i = 0; i < listView.Items.Count; i++)
{
((Label)listView.Items[i]).Content = " ";
((Label)listView.Items[i]).Tag = null;
((Label)listView.Items[i]).Background = Brushes.White;
}
}
else if (searchresult.Any())//And if there are any we set them to appropriate posistions in list;
{
for (int i = 0; i < listView.Items.Count; i++)//we go through all labels on Listview
{
Group target = searchresult.Find(delegate(Group gp)//And see if there is group for this label
{//to be displayed
return gp.Room.Id == i + 1;//We check it by room id, because each label corresponds to unique room;
});
if (target != null)//If we get some result
{
((Label)listView.Items[target.Room.Id - 1]).Tag = target;//We place this group there
((Label)listView.Items[target.Room.Id - 1]).Content = target.Room.Type + ": " +target.Name;
((Label)listView.Items[i]).Background = Brushes.LightSeaGreen;//And display with text and color;
}
else
{
((Label)listView.Items[i]).Content = " ";//Again if there is nothing - setting all to empty;
((Label)listView.Items[i]).Tag = null;
((Label)listView.Items[i]).Background = Brushes.White;
}
}
}
}
}
}
示例12: getUsersByCategoryFromDatabase
List<UserModel> getUsersByCategoryFromDatabase()
{
List<UserModel> list_user=new List<UserModel>();
for (int i = 0; i < categoryCount; i++)
{
if (category[i])
{
List<ItemTable> list = db.Items.Where(c => c.CategoryId == i + 1).ToList<ItemTable>();
foreach (ItemTable item in list)
{
UserTable user = db.Users.First(c => c.Id == item.UserId);
UserModel userModel = new UserModel()
{
AvatarUri = user.AvatarUri,
UserName = user.UserName,
Latitude=(double)user.Latitude,
Longitude = (double)user.Longitude,
Category = i,
Id=user.Id,
Address=user.Address
};
// Geocode(userModel.Address,user.Id);
if (!list_user.Any(c => c.Id == user.Id))
list_user.Add(userModel);
}
}
}
return list_user;
}
示例13: Update
public void Update(List<SimulationObject> SimObjList)
{
System.Diagnostics.Debug.WriteLine("MapManager: Update");
if (!SimObjList.Any())
return;
//Stop the engine for synchronisation reasons
_waveEngineRef.Stop();
//Debug.WriteLine("MapManager: Update");
//divide the objects in three categorys: changed wave sources, changed elong-object, changed mass, changed wall
List<SimulationObject> sources =
SimObjList.Where(o => o.GetType() == typeof (SimWaveSourceObject)).ToList();
List<SimulationObject> elongation =
SimObjList.Where(
o =>
o.ObjectType == SimulationObject.EObjectType.ConstElongation ||
o.ObjectType == SimulationObject.EObjectType.RelElongation).Where(o => o.GetType() != typeof(SimWaveSourceObject)).ToList();
List<SimulationObject> mass =
SimObjList.Where(o => o.ObjectType == SimulationObject.EObjectType.Mass).ToList();
List<SimulationObject> wall =
SimObjList.Where(o => o.ObjectType == SimulationObject.EObjectType.Wall).ToList();
//Clear all maps where objects did change, and recreate data
if (elongation.Where(o => o.PositionOrRotationChange == true).Any())
{
_additionalSettings.ElongationMap = new double[_simulationSize.Width,_simulationSize.Height];
GenerateSimObjData(elongation.Where(o => o.PositionOrRotationChange == true).ToList());
}
if (mass.Where(o => o.PositionOrRotationChange == true).Any())
{
_additionalSettings.MassMap = new double[_simulationSize.Width,_simulationSize.Height];
GenerateSimObjData(mass.Where(o => o.PositionOrRotationChange == true).ToList());
}
if (wall.Where(o => o.PositionOrRotationChange == true).Any())
{
_additionalSettings.WallMap = new bool[_simulationSize.Width,_simulationSize.Height];
GenerateSimObjData(wall.Where(o => o.PositionOrRotationChange == true).ToList());
}
//Merge _additionalSettings with _loadedSettings
//(SimObjects with mouse/stored values)
WaveSettings exportSettings = GetMergedMaps();
//Apply changes
_waveEngineRef.Settings = exportSettings;
if (sources.Where(o => o.PositionOrRotationChange == true).Any())
{
_additionalSettings.WaveSources.Clear();
_waveEngineRef.ResetSources();
GenerateSimObjData(sources);
//Add Wave Sources
//loadedSettings.sources refers directly to _waveEngine.Sources
foreach (WaveSource src in _loadedSettings.WaveSources)
{
_waveEngineRef.AddWaveSoucre(src);
}
foreach (WaveSource src in _additionalSettings.WaveSources)
{
_waveEngineRef.AddWaveSoucre(src);
}
}
//all changes done - restart the engine
_waveEngineRef.Start();
}
示例14: falar_botao_Click
private void falar_botao_Click(object sender, RoutedEventArgs e)
{
try
{
reconhecedor = new Reconhecer();
parar_botao.IsEnabled = true;
falar_botao.IsEnabled = false;
SpeechRecognitionEngine engine = reconhecedor.engine;
engine.RecognizeCompleted += engine_RecognizeCompleted;
engine.SpeechRecognized += engine_SpeechRecognized;
try
{
string linha ;
StreamReader falas = new StreamReader(Environment.CurrentDirectory + @"\Falas.txt");
List<string> ressu = new List<string>();
while((linha=falas.ReadLine())!=null){
//if(Regex.IsMatch(linha, @"^[a-zA-Z\s]+$")){
ressu.Add(linha);
//}
}
/*if (!ressu.Any())
{
MessageBox.Show("Por favor, só é permitido no arquivo de falas letras, números e espaços", "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);
}*/
falas.Close();
if (ressu.Any())
{
reconhecedor.escolhas = ressu.ToArray();
reconhecedor.gramatica = new GrammarBuilder();
reconhecedor.Recognize(RecognizeMode.Multiple);
}
else
{
MessageBox.Show("Não há nada neste arquivo.", "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);
}
//Regex.IsMatch(input, @"^[a-zA-Z]+$");
}
catch (InvalidOperationException ee)
{
MessageBox.Show("Um erro ocorreu: \n\n" + ee.Message, "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (FileNotFoundException ee)
{
MessageBox.Show("Um erro ocorreu: \n\n" + ee.Message, "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);
}
//reconhecedor.escolhas = new string[] {"fale sobre o sistema operacional","cite os planetas do sistema solar","feche o visual studio","gin defina a equivalência massa-energia","ajuda aqui", "desligar a máquina","gin feche o programa","fala teste","ajuda aqui","gin informe o clima" ,"positivo","sim","não","negativo","falas presentes"};
}
catch (InvalidOperationException ee)
{
switch (ee.Message)
{
case "Cannot find the requested data item, such as a data key or value.":
MessageBox.Show("Um erro ocorreu, talvez você não tenha um dispositivo de gravação conectado. \n\n"+ee.Message,"Erro!",MessageBoxButton.OK,MessageBoxImage.Error);
parar_botao.IsEnabled = false;
falar_botao.IsEnabled = true;
break;
default:
MessageBox.Show("Um erro ocorreu: \n\n" + ee.Message, "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);
break;
}
}
catch (Exception eee)
{
MessageBox.Show("Um erro ocorreu: \n\n" + eee.Message, "Erro...", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
示例15: CheckClipboardForNetDeckImport
private bool CheckClipboardForNetDeckImport()
{
try
{
if(Clipboard.ContainsText())
{
var clipboardContent = Clipboard.GetText();
if(clipboardContent.StartsWith("netdeckimport") || clipboardContent.StartsWith("trackerimport"))
{
var clipboardLines = clipboardContent.Split('\n').ToList();
var deckName = clipboardLines.FirstOrDefault(line => line.StartsWith("name:"));
if(!string.IsNullOrEmpty(deckName))
{
clipboardLines.Remove(deckName);
deckName = deckName.Replace("name:", "").Trim();
}
var url = clipboardLines.FirstOrDefault(line => line.StartsWith("url:"));
if(!string.IsNullOrEmpty(url))
{
clipboardLines.Remove(url);
url = url.Replace("url:", "").Trim();
}
bool? isArenaDeck = null;
var arena = clipboardLines.FirstOrDefault(line => line.StartsWith("arena:"));
if(!string.IsNullOrEmpty(arena))
{
clipboardLines.Remove(arena);
bool isArena;
if(bool.TryParse(arena.Replace("arena:", "").Trim(), out isArena))
isArenaDeck = isArena;
}
var localized = false;
var nonEnglish = clipboardLines.FirstOrDefault(line => line.StartsWith("nonenglish:"));
if(!string.IsNullOrEmpty(nonEnglish))
{
clipboardLines.Remove(nonEnglish);
bool.TryParse(nonEnglish.Replace("nonenglish:", "").Trim(), out localized);
}
var tagsRaw = clipboardLines.FirstOrDefault(line => line.StartsWith("tags:"));
var tags = new List<string>();
if(!string.IsNullOrEmpty(tagsRaw))
{
clipboardLines.Remove(tagsRaw);
tags = tagsRaw.Replace("tags:", "").Trim().Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).ToList();
}
clipboardLines.RemoveAt(0); //"netdeckimport" / "trackerimport"
var deck = ParseCardString(clipboardLines.Aggregate((c, n) => c + "\n" + n), localized);
if(deck != null)
{
if(tags.Any())
{
var reloadTags = false;
foreach(var tag in tags)
{
if(!DeckList.Instance.AllTags.Contains(tag))
{
DeckList.Instance.AllTags.Add(tag);
reloadTags = true;
}
deck.Tags.Add(tag);
}
if(reloadTags)
{
DeckList.Save();
Helper.MainWindow.ReloadTags();
}
}
if(isArenaDeck.HasValue)
deck.IsArenaDeck = isArenaDeck.Value;
deck.Url = url;
deck.Name = deckName;
SetNewDeck(deck);
if(Config.Instance.AutoSaveOnImport)
SaveDeckWithOverwriteCheck();
ActivateWindow();
}
Clipboard.Clear();
return true;
}
}
}
catch(Exception e)
{
Logger.WriteLine(e.ToString(), "NetDeckClipbardCheck");
return false;
}
return false;
}