/// <summary> /// Чтение статистики для страницы из файла /// </summary> /// <param name="url">URL страницы, для которой эта статистика</param> /// <param name="directory">Папка сохранения логов</param> /// <returns>Список статистики для страницы в случае удачи, или null в случае неудачи</returns> public static List<Stat> LoadListFromFile(string url, string directory) { List<Stat> myList = new List<Stat>(); try { if (Directory.Exists(directory)) { if (File.Exists(directory + @"\" + url.GetHashCode().ToString() + @".log")) { XmlSerializer XmlSer = new XmlSerializer(myList.GetType()); FileStream Set = new FileStream(directory + @"\" + url.GetHashCode().ToString() + @".log", FileMode.Open); myList = (List<Stat>)XmlSer.Deserialize(Set); Set.Close(); return myList; } else return null; } else return null; } catch (Exception e) { MessageBox.Show(e.Message, "Exception loading statistics", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return null; } }
public List<CombinerModel> ReadData(string fileName) { List<CombinerModel> list = new List<CombinerModel>(); object obj = CacheHelper.ReadData(ConstMember.CONFIG_CACHE_ID); if (obj == null) { string strFilePath = GetAbsolutPath(fileName); try { obj = XMLHelper.LoadFromXml(strFilePath, list.GetType()); CacheDependency dep = new CacheDependency(strFilePath); CacheHelper.WriteData(ConstMember.CONFIG_CACHE_ID, dep, obj); } catch { } } if (obj != null && obj is List<CombinerModel>) { list = obj as List<CombinerModel>; } return list; }
public void LogNameDisplaysReadablyGenerics() { var subject = new List<int>(); var logger = new Log4NetLogger(subject.GetType()); logger.Name.Should().Be("List<Int32>"); }
public Course[] GetCourses() { List<Course> holder = new List<Course>(); Console.Write(holder.GetType()); using (SqlConnection conn = new SqlConnection()) { // Create the connectionString // Trusted_Connection is used to denote the connection uses Windows Authentication conn.ConnectionString = "Data Source=tfs;Initial Catalog=study3;Integrated Security=True"; conn.Open(); // Create the command SqlCommand command = new SqlCommand("SELECT * FROM db_owner.course", conn); //// Add the parameters. //command.Parameters.Add(new SqlParameter("0", 1)); // Use a SqlDataReader to read the results from the SqlCommand using (SqlDataReader reader = command.ExecuteReader()) { foreach (IDataRecord record in reader) { string[] dataRow = ReadSingleRow((IDataRecord)reader); //Course courseHolder = new Course(dataRow); //holder.Add(courseHolder); } } } Course[] returnCourseArray = holder.ToArray(); return returnCourseArray; }
/// <summary> /// Loads the highscores from isolated storage /// </summary> static public void Load() { scores = new List<HighscoreItem>(); IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); // Create empty list if the highscores file does not exist. // This is needed when the application is started for the first time. if (!store.FileExists(highscoresFilename)) { for (int i = 1; i <= 20; i++) { scores.Add(new HighscoreItem(i, "Sudokumaster", new TimeSpan(0, 59, 59), 100)); } Save(); return; } // Open the file and use XmlSerializer to deserialize the xml file into // a list of HighscoreItems. using (IsolatedStorageFileStream stream = store.OpenFile(highscoresFilename, FileMode.Open)) { using (StreamReader reader = new StreamReader(stream)) { XmlSerializer serializer = new XmlSerializer(scores.GetType()); scores = (List<HighscoreItem>)serializer.Deserialize(reader); } } }
public void SaveGuitars(List<Guitar> guitars) { var serializer = new XmlSerializer(guitars.GetType()); TextWriter tw = new StreamWriter(Path); serializer.Serialize(tw, guitars); tw.Close(); }
/// <summary> /// MA: moving average /// An often used helper method which take in a list of values (of consecutive /// days) and calculates the moving average /// </summary> /// <param name="values">a list of certain length of values of different dates</param> /// <returns>MA</returns> public static double[] MACalculator(List<double> values) { double[] resultArray = new double[6]; double sum = 0.0; int days = 0; if (values.Count >= 250) { for (int i = 0; i <= 249; i++) { sum += values[i]; if (values.GetType().Name != "DBNull") days++; if (i == 4) resultArray[0] = sum / days; else if (i == 9) resultArray[1] = sum / days; else if (i == 19) resultArray[2] = sum / days; else if (i == 59) resultArray[3] = sum / days; else if (i == 119) resultArray[4] = sum / days; else if (i == 249) resultArray[5] = sum / days; } } else { Console.WriteLine("data not available, needs to wait for 250 days"); } return resultArray; }
/// <summary> /// 通过文件名获取配置 /// </summary> /// <param name="fileName">配置文件名不带后缀的</param> /// <returns></returns> public static List<VarItem> Load(string fileName) { //如果缓存里面有这个配置就直接返还 if (dataCache.ContainsKey(fileName)&& dataCache[fileName] != null) return dataCache[fileName]; //如果缓存里没这个配置就第一次读取 string path = GetDefaultConfigPath(fileName); //校验是路径是否有效 if (File.Exists(path) == false) throw new FileNotFoundException("文件没找到", path); //读取 List<VarItem> items = new List<VarItem>(); XmlSerializer xmlSerializer = new XmlSerializer(items.GetType()); FileStream fs = new FileStream(path, FileMode.Open); using (fs) { try { items = xmlSerializer.Deserialize(fs) as List<VarItem>; } catch (InvalidOperationException ex) { throw ; } } //如果配置没有内容可能会读到空的items,不过这是允许的。 dataCache.Add(fileName, items); return items; }
public void TypeConverterListBool_CanConvert(object value, bool isConvertable) { var converter = new TypeConverter<IEnumerable<bool>>(); var list = new List<bool> {false, true}; var canConvert = converter.CanConvert(list.GetType()); Assert.True(canConvert); }
public static void Main (string[] args) { var coll = new List<int>() { 5, 25, 50, 125 }; var arr = coll.ToArray(); Console.WriteLine("{0} {1}", coll.GetType(), arr.GetType()); Console.WriteLine("{0} {1}", coll[0].GetType(), arr[0].GetType()); }
public static void DisplayAllWord(List<string> ls) { Type t = ls.GetType(); Console.WriteLine("list of {0} contein", t.Name); foreach (string s in ls) Console.WriteLine(s); }
static void Main(string[] args) { // Use var for an array. // Note the use of the new implicitly typed array syntax. // The compiler looks at the initialization list and infers that the // array type you want is int[]. var numbers = new[] { 1, 2, 3 }; Console.WriteLine("Array initializer: "); foreach (int n in numbers) { Console.WriteLine(n.ToString()); } // This writes "System.Int32[]". Console.WriteLine(numbers.GetType().ToString()); Console.WriteLine(); // Use var for a generic list type. // Note the use of the new collection initializer syntax, too. var names = new List<string> { "Chuck", "Bob", "Steve", "Mike" }; Console.WriteLine("List of names: "); foreach (string s in names) { Console.WriteLine(s); } // This writes "System.Collections.Generic.List`1[System.String]". // Note that the compiler calls any List<T> a List`1. // To look up List<T> in the documentation, specify "List<T>". Console.WriteLine(names.GetType().ToString()); Console.WriteLine(); // Wait for user to acknowledge results. Console.WriteLine("Press Enter to terminate..."); Console.Read(); }
static UserStore() { _users = new List<User>(); XmlSerializer serializer = new XmlSerializer(_users.GetType(), new XmlRootAttribute("Users")); if (File.Exists("users.xml")) { _users = serializer.Deserialize(new StreamReader("users.xml")) as List<User>; } else { _users.Add(new User { Username = "******", Password = "******", HomeDir = "C:\\Utils", //TwoFactorSecret = "1234567890", // Base32 Encoded: gezdgnbvgy3tqojq }); using (StreamWriter w = new StreamWriter("users.xml")) { serializer.Serialize(w, _users); } } }
static void Main(string[] args) { Type guyType = typeof(Guy); Console.WriteLine("{0} extends {1}", guyType.FullName, guyType.BaseType.FullName); // output: TypeExamples.Guy extends System.Object Type nestedClassType = typeof(NestedClass.DoubleNestedClass); Console.WriteLine(nestedClassType.FullName); // output: TypeExamples.Program+NestedClass+DoubleNestedClass List<Guy> guyList = new List<Guy>(); Console.WriteLine(guyList.GetType().Name); // output: List`1 Dictionary<string, Guy> guyDictionary = new Dictionary<string, Guy>(); Console.WriteLine(guyDictionary.GetType().Name); // output: Dictionary`2 Type t = typeof(Program); Console.WriteLine(t.FullName); // output: TypeExamples.Program Type intType = typeof(int); Type int32Type = typeof(Int32); Console.WriteLine("{0} - {1}", intType.FullName, int32Type.FullName); // System.Int32 - System.Int32 Console.WriteLine("{0} {1}", float.MinValue, float.MaxValue); // output:-3.402823E+38 3.402823E+38 Console.WriteLine("{0} {1}", int.MinValue, int.MaxValue); // output:-2147483648 2147483647 Console.WriteLine("{0} {1}", DateTime.MinValue, DateTime.MaxValue); // output: 1/1/0001 12:00:00 AM 12/31/9999 11:59:59 PM Console.WriteLine(12345.GetType().FullName); // output: System.Int32 Console.ReadKey(); }
private void databinding(List<RFDeviceAPP.Common.NSPRFIQ01.Response.UtilityHeader> list) { this.dataGridTableStyle1.MappingName = list.GetType().Name; this.dataGrid1.TableStyles.Clear(); this.dataGrid1.TableStyles.Add(this.dataGridTableStyle1); this.dataGrid1.DataSource = list; }
private void Form1_Load(object sender, EventArgs e) { if (ItemsFile.Exists) { List<ItemInfo> lst = new List<ItemInfo>(); XmlSerializer xml = new XmlSerializer(lst.GetType()); using (Stream s = ItemsFile.OpenRead()) { lst = xml.Deserialize(s) as List<ItemInfo>; } foreach (ItemInfo item in lst) { CalendarItem cal = new CalendarItem(calendar1, item.StartTime, item.EndTime, item.Text); if (!(item.R == 0 && item.G == 0 && item.B == 0)) { cal.ApplyColor(Color.FromArgb(item.A, item.R, item.G, item.B)); } _items.Add(cal); } PlaceItems(); } }
private static void CreateSampleQueries() { var queries = new List<Query> { new Query { OrderBy = "Id", OutputFileName = "Result0.xml", WhereClauses = new List<WhereClause> { new WhereClause { PropertyName = "City", Type = "Equals", Value = "Sofia" }, new WhereClause { PropertyName = "Year", Type = "GreaterThan", Value = "1999" } } } }; var serializer = new XmlSerializer(queries.GetType(), new XmlRootAttribute("Queries")); using (var fs = new FileStream("Queries.xml", FileMode.Create)) { serializer.Serialize(fs, queries); } }
public List<TranferLayer> DeserializeXmlFile() { List<TranferLayer> dataLayers = new List<TranferLayer>(); try { XmlSerializer ser = new XmlSerializer(dataLayers.GetType()); if (!File.Exists(lm.PathToXMLFile)) return dataLayers; using (XmlReader reader = XmlReader.Create(lm.PathToXMLFile)) { try { dataLayers = (List<TranferLayer>)ser.Deserialize(reader); } catch (Exception ex) { } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error); } return dataLayers; }
static FtpUserStore() { _users = new List<FtpUser>(); XmlSerializer serializer = new XmlSerializer(_users.GetType(), new XmlRootAttribute("Users")); if (File.Exists("users.xml")) { _users = serializer.Deserialize(new StreamReader("users.xml")) as List<FtpUser>; } else { _users.Add(new FtpUser { UserName = "******", Password = "******", HomeDir = "C:\\Utils" }); using (StreamWriter w = new StreamWriter("users.xml")) { serializer.Serialize(w, _users); } } }
public void SaveAmplifiers(List<Amplifier> amplifiers) { var serializer = new XmlSerializer(amplifiers.GetType()); TextWriter tw = new StreamWriter(@"d:\guitarweb\amplifiers.xml"); serializer.Serialize(tw, amplifiers); tw.Close(); }
public void Can_convert_string_list_to_string() { var items = new List<string> {"foo", "bar", "day"}; var converter = TypeDescriptor.GetConverter(items.GetType()); var result = converter.ConvertTo(items, typeof (string)) as string; result.ShouldNotBeNull(); result.ShouldEqual("foo,bar,day"); }
private static Dictionary<string, string> ReadTranslationData() { List<UserData> userStringList = new List<UserData>(); XmlSerializer serializer = new XmlSerializer(userStringList.GetType()); userStringList = (List<UserData>)serializer.Deserialize(XmlReader.Create(SettingsPath)); return userStringList.ToDictionary(n => n.Tag, n => n.Text.Replace("__BREAK__", Environment.NewLine)); }
public void SaveTimesheeets(List<Timesheet> timesheets) { var serializer = new XmlSerializer(timesheets.GetType()); using (TextWriter streamWriter = new StreamWriter(Settings.Default.XMLFileName)) { serializer.Serialize(streamWriter, timesheets); } }
public void Save(List<Entree> rank) { using (FileStream str = File.Create("sav.xml")) { XmlSerializer bf = new XmlSerializer(rank.GetType()); bf.Serialize(str, rank); } }
public void print(List<string> input) { Console.WriteLine("Collection: " + input.GetType()); foreach (var item in input) { Console.Write("{0}", item); } }
public static List<LinkConfig> GetConfiguration(string name) { List<LinkConfig> con = new List<LinkConfig>(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(name); XmlSerializer ser = new XmlSerializer(con.GetType()); return (List<LinkConfig>)ser.Deserialize(new StringReader(xmlDoc.InnerXml)); }
public void Serialize(List<MessageModel> messages, string fileName) { var serializer = new XmlSerializer(messages.GetType()); using (var fileStream = new FileStream(fileName, FileMode.Create)) { serializer.Serialize(fileStream, messages); } }
private static List<SystemNotificationPreference> Deserialize(String tbd) { List<SystemNotificationPreference> l = new List<SystemNotificationPreference>(); XmlSerializer serializer = new XmlSerializer(l.GetType()); using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(tbd))) { return (List<SystemNotificationPreference>)serializer.Deserialize(stream); } }
public void Can_convert_int_list_to_string() { var items = new List<int> {10, 20, 30, 40, 50}; var converter = TypeDescriptor.GetConverter(items.GetType()); var result = converter.ConvertTo(items, typeof (string)) as string; result.ShouldNotBeNull(); result.ShouldEqual("10,20,30,40,50"); }
public void AllSongsAcquired(List<GoogleMusicSong> songs) { var ms = new MemoryStream (); var utf8 = System.Text.Encoding.UTF8; using (var ifs = IsolatedStorageFile.GetUserStoreForApplication ()) using (var fs = ifs.CreateFile ("all_songs.lst")) new DataContractJsonSerializer (songs.GetType ()).WriteObject (fs, songs.ToArray ()); this.RunOnUiThread (() => Toast.MakeText (this, "downloaded song list", ToastLength.Short)); }
protected virtual async Task <List <T> > GetAllPageDataResultsAsync <T>(IPageDataRequest pageDataRequest, Func <IPageDataRequest, Task <IHttpCallResultCGHT <IPageDataT <IList <T> > > > > getMethodToRun, bool throwExceptionOnFailureStatusCode = false) { List <T> retVal = new List <T>(); IHttpCallResultCGHT <IPageDataT <IList <T> > > response = null; IPageDataRequest currentPageDataRequest = new PageDataRequest(pageDataRequest.FilterCriteria, pageDataRequest.Sort, pageDataRequest.Page, pageDataRequest.PageSize); while (response == null || (response.IsSuccessStatusCode == true && currentPageDataRequest.Page <= response.Data.TotalPages)) { response = await getMethodToRun(currentPageDataRequest); if (response.IsSuccessStatusCode && response.Data != null) { retVal.AddRange(response.Data.Data); } else { string serializedCurrentPageDataRequest = JsonConvert.SerializeObject(currentPageDataRequest); string msg = $"{nameof(GetAllPageDataResultsAsync)} call resulted in error - status code: {response?.StatusCode}; reason: {response?.ReasonPhrase}. CurrentPageDataRequest: {serializedCurrentPageDataRequest}"; Log.LogWarning(eventId: (int)coreEnums.EventId.Warn_WebApiClient, exception: response?.Exception, message: "Failure during WebApiClient to Web API GetAllPage operation with {ReturnTypeName}. ReasonPhrase: {ReasonPhrase} HttpResponseStatusCode: {HttpResponseStatusCode} using CurrentPageDataRequest: {CurrentPageDataRequest}", retVal?.GetType().Name, response?.ReasonPhrase, (int)response.StatusCode, serializedCurrentPageDataRequest); if (throwExceptionOnFailureStatusCode == true) { throw new ApplicationException(msg, response?.Exception); } } currentPageDataRequest.Page += 1; } return(retVal); }
private static bool Prefix(List <StorageUnit> __instance, StorageUnit item) { // fix for https://github.com/pardeike/Harmony/issues/156 if (__instance?.GetType() != typeof(List <StorageUnit>)) { return(true); } if (!Enabled) { return(true); } try { __instance.InsertSorted(item, StorageComparer); Main.Logger.Debug <SortChestsByName>($"Inserted [{item.StorageName}] in order."); return(false); } catch (Exception exception) { Main.Logger.Exception(exception); } return(true); }
public void Sit( string message, int howManyTimes, byte[] whatEvenIs = null, Guid[][] whatEvenIsThis = null, T1[][][] whatEvenIsThisT = null, List <byte[][]> evenMoreWhatIsThis = null, List <DogTrick <T1> > previousTricks = null, Tuple <int, T1, string, object, Tuple <Tuple <T2, long>, long>, Task, Guid> tuple = null, Dictionary <int, IList <Task <DogTrick <T1> > > > whatAmIDoing = null) { for (var i = 0; i < howManyTimes; i++) { message += message + whatEvenIs?.ToString() + whatEvenIsThis?.ToString() + whatEvenIsThisT?.ToString() + evenMoreWhatIsThis?.GetType() + previousTricks?.GetType() + tuple?.GetType() + whatAmIDoing?.GetType(); } }
static void Main(string[] args) { List <Car> myCars = new List <Car>() { new Car() { VIN = "A1", Make = "BMW", Model = "550i", StickerPrice = 55000, Year = 2009 }, new Car() { VIN = "B2", Make = "Toyota", Model = "4Runner", StickerPrice = 35000, Year = 2010 }, new Car() { VIN = "C3", Make = "BMW", Model = "745li", StickerPrice = 75000, Year = 2008 }, new Car() { VIN = "D4", Make = "Ford", Model = "Escape", StickerPrice = 25000, Year = 2008 }, new Car() { VIN = "E5", Make = "BMW", Model = "55i", StickerPrice = 57000, Year = 2010 } }; //LINQ query /* * var bmws = from car in myCars * where car.Make == "BMW" * && car.Year == 2010 * select car; */ /* * var orderedCars = from car in myCars * orderby car.Year descending * select car; */ //LINQ method //var bmws = myCars.Where(p => p.Make == "BMW" && p.Year == 2010); //var orderedCars = myCars.OrderByDescending(p => p.Year); /* * var firstBMW = myCars.OrderByDescending(p => p.Year).First(p => p.Make == "BMW"); * Console.WriteLine(firstBMW.VIN); */ //Console.WriteLine(myCars.TrueForAll(p => p.Year > 2007)); //myCars.ForEach(p => p.StickerPrice -= 3000); //myCars.ForEach(p => Console.WriteLine("{0} {1:C}", p.VIN, p.StickerPrice)); //Console.WriteLine(myCars.Exists(p => p.Model == "745li")); //Console.WriteLine(myCars.Sum(p => p.StickerPrice)); /* * foreach (var car in orderedCars) * { * Console.WriteLine("{0} {1}", car.Year, car.Model, car.VIN); * } */ Console.WriteLine(myCars.GetType()); var newCars = from car in myCars where car.Make == "BMW" && car.Year == 2010 select new { car.Make, car.Model }; Console.WriteLine(newCars.GetType()); Console.ReadLine(); }
public static void GetInfo(List <T> items) { T first = items[0]; Console.WriteLine($"This list has {items.Count} members and is of type {items.GetType().FullName}!"); }
static void Main(string[] args) { List <Car> myCars = new List <Car>() { new Car() { VIN = "A1", Make = "BMW", Moddel = "550i", StcikerPrice = 55000, Year = "1999" }, new Car() { VIN = "B2", Make = "4Runner", Moddel = "SUV", StcikerPrice = 55000, Year = "1999" }, new Car() { VIN = "C3", Make = "BMW", Moddel = "300", StcikerPrice = 35000, Year = "2011" }, new Car() { VIN = "D4", Make = "Ford", Moddel = "Escape", StcikerPrice = 25000, Year = "2006" }, new Car() { VIN = "E5", Make = "BMW", Moddel = "55i", StcikerPrice = 57000, Year = "2010" }, }; // Two sperate LINQ methods LINQ QUERY AND METHOD //LINQ query var bmws = from car in myCars where car.Make == "BMW" && car.Year == 2010 //&& must fill this operation and this operation. select car //LINQ method var BMWs = myCars.Where(p => p.Make == "BMW" && p.Year == "2010"); //add the method your calling to the subset BMW. Create a collection, start with previous collection, put something it it depending on criteria, we are picking something where the item has a certain property BMW and that item has a certain year. You need var bmws so LINQ knows what you are refferring too. var ordererdCars = from car in myCars orderby car.Year desecnding select car; //Or// var orderedCars = myCars.OrderByDescending(p => p.Year); // given each item in p we want to order by Year //Or// var firstBMW = myCars.First(p => p.Make = "BMW"); // Order by First //Together// var firstBMW = myCars.OrderByDescending(p => p.Year).First(p => p.Make == "BMW"); Console.WriteLine(firstBMW.VIN); //Chaining the two together // running through cars Console.WriteLine(myCars.TrueForAll(p => p.Year > 2012)); //Are all cars greater than 2012? // checks through every car //Otherwise foreach myCars.ForEach(p => Console.WriteLine("{0} {1:C}", p.VIN, p.StickerPrice)); //another example myCars.ForEach(p => p.StickerPrice -= 3000); //or Console.WriteLine(myCars.Exists(p => p.Model == "745li")); // another aggregiate Console.WriteLine(myCars.Sum(p => p.StickerPrice)); Console.WriteLine(myCars.GetType()); // defines method called get type which will tell you the type of a given object printed to screen. foreach (var item in bmws) { Console.WriteLine("{0}, {1}", car.Year, car.Model, car.VIN); } Console.ReadLine(); }
static void Main(string[] args) { string[] names = { "David", "Jack", "Suzie" }; var resultAsEnumerable = names.AsEnumerable();//AsEnumerable: casts a collection to IEnumerable of same type. Console.WriteLine("Iterating over IEnumerable collection:"); foreach (var name in resultAsEnumerable) { Console.WriteLine(name); } List <string> cars = new List <string> { "BMW", "Mercedes", "Lexus" }; //This Lambda Expression sample casts list of strings to a simple string array. var resultCast = names.Cast <string>();//Cast: Casts a collection to a specified type. Console.WriteLine("List of cars casted to a simple string array:"); foreach (string car in resultCast) { Console.WriteLine(car); } object[] objects = { "Man", 100, 9.9, true, null }; var resultOfTypeString = objects.OfType <string>();// OfType: Filters elements of specified type in a collection. Console.WriteLine("Objects being of type string have the values:"); foreach (string str in resultOfTypeString) { Console.WriteLine(str); } var resultOfTypeInt = objects.OfType <int>();// OfType: Filters elements of specified type in a collection. Console.WriteLine("Objects being of type int have the values:"); foreach (int number in resultOfTypeInt) { Console.WriteLine(number); } var resultOfTypeBoolean = objects.OfType <bool>();// OfType: Filters elements of specified type in a collection. Console.WriteLine("Objects being of type bool have the values:"); foreach (bool value in resultOfTypeBoolean) { Console.WriteLine(value); } int[] numbers = { 1, 2, 3, 4, 5 }; //ToArray: Converts type to a new array. var resultToArray = numbers.ToArray();//This Lambda Expression sample converts one array to another. Console.WriteLine("New array contains identical values:"); foreach (int number in resultToArray) { Console.WriteLine(number); } English2German[] english2German = { new English2German { EnglishSalute = "Good morning", GermanSalute = "Guten Morgen" }, new English2German { EnglishSalute = "Good day", GermanSalute = "Guten Tag" }, new English2German { EnglishSalute = "Good evening", GermanSalute = "Guten Abend" }, }; //ToDictionary: Converts collection into a Dictionary with Key and Value. var resultToDictionarySimple = english2German.ToDictionary(k => k.EnglishSalute, v => v.GermanSalute); Console.WriteLine("Values inserted into dictionary:"); foreach (KeyValuePair <string, string> dic in resultToDictionarySimple) { Console.WriteLine(String.Format($"English salute {dic.Key} is {dic.Value} in German")); } int[] numbersDict = { 1, 2, 3, 4, 5 }; //ToDictionary: Converts collection into a Dictionary with Key and Value. //This Lambda Expression sample uses ToDictionary to make a new array based on condition. var result = numbersDict.ToDictionary(k => k, v => (v % 2) == 1 ? "Odd" : "Even"); Console.WriteLine("Numbers labeled Odd and Even in dictionary:"); foreach (var dictionary in result) { Console.WriteLine($"Value {dictionary.Key} is {dictionary.Value}"); } string[] namesToList = { "Jack", "David", "Alex" }; //ToList: Converts collection into a List. // This Lambda Expression sample converts string array to List of strings. List <string> resultToList1 = namesToList.ToList(); Console.WriteLine($"name is of type {namesToList.GetType().Name}"); Console.WriteLine($"result is of type {namesToList.GetType().Name}"); int[] numbersToList = { 1, 2, 3, 4, 5 }; //ToList: Converts collection into a List. // This Lambda Expression sample converts int array to List of int. List <int> resultToList2 = numbersToList.ToList(); Console.WriteLine($"number is of type {numbersToList.GetType().Name}"); Console.WriteLine($"result2 is of type {resultToList2.GetType().Name}"); string[] wordsArray = { "one", "two", "three", "four", "five", "six", "seven" }; //ToLookup: Converts a collection into a Lookup, grouped by key. //This Lambda Expression sample puts array elements into a one-to-many Lookup, where key equals element length. var resultToLookUp = wordsArray.ToLookup(w => w.Length); for (int i = 1; i <= 5; i++) { Console.WriteLine(String.Format($"Elements with a length of {i}:")); foreach (string word in resultToLookUp[i]) { Console.WriteLine(word); } } Console.WriteLine("Hello World!"); }
static DataTable GenericListToDataTable(List <T> list) { DataTable dt = null; Type listType = list.GetType();//IsGenericType var sp = Spring; string TableName = sp.TableName, PKName = sp.PKName, Columns = sp.Columns; var 自增编号 = sp.IdentityPK; //determine the underlying type the List<> contains Type elementType = listType.GetGenericArguments()[0]; //create empty table -- give it a name in case //it needs to be serialized dt = new DataTable(TableName); //define the table -- add a column for each public //property or field MemberInfo[] miArray = elementType.GetMembers( BindingFlags.Public | BindingFlags.Instance); foreach (MemberInfo mi in miArray) { if (mi.MemberType == MemberTypes.Property) { PropertyInfo pi = mi as PropertyInfo; var piName = pi.Name; if (((string.IsNullOrWhiteSpace(Columns) || Columns.Equals("*")) || Columns.IndexOf(piName) != -1) && (!(piName.Equals(PKName) && 自增编号))) { dt.Columns.Add(piName, pi.PropertyType); } } else if (mi.MemberType == MemberTypes.Field) { FieldInfo fi = mi as FieldInfo; var piName = fi.Name; if (((string.IsNullOrWhiteSpace(Columns) || Columns.Equals("*")) || Columns.IndexOf(piName) != -1) && (!(piName.Equals(PKName) && 自增编号))) { dt.Columns.Add(piName, fi.FieldType); } } } foreach (var record in list) { int i = 0; object[] fieldValues = new object[dt.Columns.Count]; foreach (DataColumn c in dt.Columns) { MemberInfo mi = elementType.GetMember(c.ColumnName)[0]; if (mi.MemberType == MemberTypes.Property) { PropertyInfo pi = mi as PropertyInfo; fieldValues[i] = pi.GetValue(record, null); } else if (mi.MemberType == MemberTypes.Field) { FieldInfo fi = mi as FieldInfo; fieldValues[i] = fi.GetValue(record); } i++; } dt.Rows.Add(fieldValues); } return(dt); }
public User_cart() { InitializeComponent(); if (File.Exists("CustomersCart.xml")) { Double total = 0; DGV_customerCart.Rows.Clear(); DGV_customerCart.Refresh(); XmlSerializer ser = new XmlSerializer(typeof(List <CustomerCart>)); FileStream fs = new FileStream("CustomersCart.xml", FileMode.Open); customers = (List <CustomerCart>)ser.Deserialize(fs); fs.Close(); XmlDocument doc = new XmlDocument(); doc.Load("CustomersCart.xml"); XmlNodeList cart = doc.GetElementsByTagName("food"); for (int i = 0; i < cart.Count; i++) { String Order_ID = cart[i].ChildNodes[0].InnerText; String Quantity = cart[i].ChildNodes[2].InnerText; String Total_Price = cart[i].ChildNodes[1].InnerText; DGV_customerCart.Rows.Add(Order_ID, Quantity, Total_Price); total += Convert.ToDouble(Total_Price); } Total_purchase.Text = total.ToString(); XmlDocument xml = new XmlDocument(); xml.Load("DeliveryBoys.xml"); XmlNodeList Area_list = xml.GetElementsByTagName("Assigned_Area"); for (int c = 0; c < Area_list.Count; c++) { int count = 0; if (address_txt.Items.Count == 0) { address_txt.Items.Add(Area_list[c].InnerText); } else { for (int j = 0; j < address_txt.Items.Count; j++) { if (!Area_list[c].InnerText.Equals(address_txt.Items[j])) { count++; } else { break; } } if (count == address_txt.Items.Count) { address_txt.Items.Add(Area_list[c].InnerText); } } } } if (File.Exists("Customers.xml")) { XmlSerializer ser = new XmlSerializer(customer.GetType()); FileStream fs = new FileStream("Customers.xml", FileMode.Open); customer = (List <CustomerDetails>)ser.Deserialize(fs); fs.Close(); } if (File.Exists("Delivery.xml")) { XmlSerializer xml = new XmlSerializer(typeof(List <Deliivery>)); FileStream Stream = new FileStream("Delivery.xml", FileMode.Open); delivery = (List <Deliivery>)xml.Deserialize(Stream); Stream.Close(); } }
protected void Page_Load(object sender, EventArgs e) { TwitterContext twitterCtx = new TwitterContext(); List <string> locations = new List <string>(); int count = 0; string name = string.Empty; string latitude = string.Empty; string longitude = string.Empty; List <Data> outputList = new List <Data>(); string url = string.Empty; string customLoc = Request.Params["Location"]; if (!String.IsNullOrEmpty(customLoc)) { if (customLoc == "Default") // Custom location not defined { // Find out the locations where trends are most concentrated var trends = from trnd in twitterCtx.Trends where trnd.Type == TrendType.Available select trnd; var trend = trends.FirstOrDefault(); trend.Locations.ToList().ForEach( loc => locations.Add(loc.WoeID)); } else { locations = getNearbyLocations(customLoc); } // Convert every woeID into coordinates foreach (string woeID in locations) { // Only find the top 10 if (count > 10) { break; } bool isDone = false; url = String.Format("http://where.yahooapis.com/v1/place/{0}?appid={1}", woeID, APP_ID); XmlTextReader oXmlReader = new XmlTextReader(url); string eName = string.Empty; while (oXmlReader.Read() && !isDone) { switch (oXmlReader.NodeType) { case XmlNodeType.Element: eName = oXmlReader.Name; break; case XmlNodeType.Text: switch (eName) { case "name": name = oXmlReader.Value; break; case "latitude": latitude = oXmlReader.Value; break; case "longitude": longitude = oXmlReader.Value; isDone = true; break; } break; } } // Find the top trends for each location if (woeID != null) { try { var queries = (from trnd in twitterCtx.Trends where trnd.Type == TrendType.Location && trnd.WeoID == int.Parse(woeID) select trnd) .ToList(); outputList.Add(new Data { Name = name, Latitude = latitude, Longitude = longitude, Trend1 = queries[0].Name, Query1 = queries[0].Query, Trend2 = queries[1].Name, Query2 = queries[1].Query, Trend3 = queries[2].Name, Query3 = queries[2].Query }); count++; } catch (Exception ex) { Page page = HttpContext.Current.Handler as Page; if (page != null) { string textForMessage = "Error: could not find any trends for " + name; ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + textForMessage + "');", true); } } } } DataContractJsonSerializer serializer = new DataContractJsonSerializer(outputList.GetType()); MemoryStream ms = new MemoryStream(); //serialize the object to memory stream serializer.WriteObject(ms, outputList); //convert the serizlized object to string string jsonString = Encoding.Default.GetString(ms.ToArray()); ms.Close(); if (Page.ClientQueryString.Length > 0) { Response.Write(jsonString); } } }
public static void op_ResolveToken(Tokenizer tok, Token token, object scope, out object value, out Type type) { value = token.Resolve(tok, scope); type = (value != null) ? value.GetType() : null; if (scope == null || type == null) { return; } // no scope, or no data, easy. we're done. string name = value as string; if (name == null) // data not a string (can't be a reference from scope), also easy. done. { List <object> args = value as List <object>; if (args != null) { for (int i = 0; i < args.Count; ++i) { bool remove = false; op_ResolveToken(tok, new Token(args[i], -1, -1), scope, out value, out type); switch (value as string) { case ",": remove = true; break; } if (remove) { args.RemoveAt(i--); } else { args[i] = value; } } value = args; type = args.GetType(); } return; } Context.Entry e = token.GetAsContextEntry(); if (e != null && e.IsText()) { return; } // data is explicitly meant to be a string, done. switch (name) { case "null": value = null; type = null; return; case "true": value = true; type = typeof(bool); return; case "false": value = false; type = typeof(bool); return; } // otherwise, we search for the data within the given context Type scopeType = scope.GetType(); KeyValuePair <Type, Type> dType = scopeType.GetIDictionaryType(); if (dType.Key != null) { if (dType.Key == typeof(string) && (name[0] == (Parser.Wildcard) || name[name.Length - 1] == (Parser.Wildcard))) { MethodInfo getKey = null; IEnumerator en = (IEnumerator)scopeType.GetMethod("GetEnumerator", Type.EmptyTypes).Invoke(scope, new object[] { }); //foreach(var kvp in dict) { while (en.MoveNext()) { object kvp = en.Current; if (getKey == null) { getKey = kvp.GetType().GetProperty("Key").GetGetMethod(); } string memberName = getKey.Invoke(kvp, null) as string; if (Parser.IsWildcardMatch(memberName, name)) { name = memberName; break; } } } // how to generically interface with standard Dictionary objects IDictionary dict = scope as IDictionary; if (dict != null) { if (dict.Contains(name)) { value = dict[name]; } } else { // how to generically interface with a non standard dictionary MethodInfo mi = scopeType.GetMethod("ContainsKey", new Type[] { dType.Key }); bool hasIt = (bool)mi.Invoke(scope, new object[] { name }); if (hasIt) { mi = scopeType.GetMethod("Get", new Type[] { dType.Key }); value = mi.Invoke(scope, new object[] { name }); } } type = (value != null) ? value.GetType() : null; return; } if (name[0] == (Parser.Wildcard) || name[name.Length - 1] == (Parser.Wildcard)) { FieldInfo[] fields = scopeType.GetFields(); string[] names = Array.ConvertAll(fields, f => f.Name); int index = Parser.FindIndexWithWildcard(names, name, false); if (index >= 0) { //Show.Log(name+" "+scopeType+" :"+index + " " + names.Join(", ") + " " +fields.Join(", ")); value = fields[index].GetValue(scope); type = (value != null) ? value.GetType() : null; return; } PropertyInfo[] props = scopeType.GetProperties(); names = Array.ConvertAll(props, p => p.Name); index = Parser.FindIndexWithWildcard(names, name, false); if (index >= 0) { value = props[index].GetValue(scope, null); type = (value != null) ? value.GetType() : null; return; } } else { FieldInfo field = scopeType.GetField(name); if (field != null) { value = field.GetValue(scope); type = (value != null) ? value.GetType() : null; return; } PropertyInfo prop = scopeType.GetProperty(name); if (prop != null) { value = prop.GetValue(scope, null); type = (value != null) ? value.GetType() : null; return; } } }
/// <summary> /// 功能描述:修改数据(如果实体启用记录修改字段功能,则修改主键可用,否则请重新该函数并使用dal的UpdateEx函数进行处理) /// </summary> /// <param name="strJson">strJson</param> /// <returns>返回值</returns> public virtual string Update(string strJson) { TEntity entity = strJson.ToJsonObject <TEntity>(); try { Type type = entity.GetType(); //取的LstModifyFields PropertyInfo pi = type.GetProperty("LstModifyFields"); Dictionary <string, object> LstModifyFields = null; if (pi != null) { LstModifyFields = pi.GetValue(entity, null) as Dictionary <string, object>; } //是否修改内容包含主键 bool blnIsHas = false; bool blnUpdate = false; if (LstModifyFields != null && LstModifyFields.Count > 0) { List <string> lst = LstModifyFields.Keys.ToList(); MethodInfo miIsHasPrimaryKey = type.GetMethod("IsHasPrimaryKey", new Type[] { lst.GetType() }); blnIsHas = (bool)miIsHasPrimaryKey.Invoke(entity, new object[] { lst }); } if (blnIsHas) { //处理包含主键的修改 MethodInfo miCreateWhereDictWithModifyFields = type.GetMethod("CreateWhereDictWithModifyFields", new Type[] { }); Dictionary <string, object> lstDicWhere = (Dictionary <string, object>)miCreateWhereDictWithModifyFields.Invoke(entity, null); blnUpdate = dal.UpdateEx(entity, LstModifyFields.Keys.ToList(), lstDicWhere); } else { //普通修改 blnUpdate = dal.Update(entity, LstModifyFields == null ? null : LstModifyFields.Keys.ToList(), null); } if (pi != null) { MethodInfo mi = entity.GetType().GetMethod("ClearRecord"); if (mi != null) { mi.Invoke(entity, null); } } if (blnUpdate) { return(ExcuteMessage.Sucess(entity)); } else { return(ExcuteMessage.Error("更新失败。")); } } catch (Exception ex) { return(ExcuteMessage.ErrorOfException(ex)); } }
public void Can_parse_string_list_with_special_chars_as_object() { var stringList = new List <string> { "\"1st", "2:nd", "3r,d", "four%" }; const string listValues = "[\"\"\"1st\",2:nd,\"3r,d\",four%]"; var parsedList = TypeSerializer.DeserializeFromString(listValues, stringList.GetType()); Assert.That(parsedList, Is.EquivalentTo(stringList)); Serialize(stringList); }
private void Consultar() { try { string HTMLRetornado = string.Empty; lblMensagemRetorno.Text = ""; lblMensagemRetorno.Visible = false; divEspacoBranco.Visible = false; divResultado.Visible = false; divImprimirMensagemErro.Attributes.Add("style", "display:none;"); Negocios.Cadastral.WEB.RastreamentoSearchPF n = new Negocios.Cadastral.WEB.RastreamentoSearchPF(); List <Entidades.Cadastral.ResponseSearchPF> listRet = new List <Entidades.Cadastral.ResponseSearchPF>(); Entidades.Cadastral.FiltroPesquisaSearchPF filtro = new Entidades.Cadastral.FiltroPesquisaSearchPF(); filtro.Nome = txtNome.Text.ToUpper(); filtro.UF = ddlUF.SelectedItem.Text.Split(new Char[] { '-' })[0].ToString().Trim();; filtro.Cidade = Util.Format.RemoverAcentos(ddlCidade.SelectedItem.Text); filtro.DataNascimento = txtDataNascimento.Text; filtro.NomeMae = txtNomeMae.Text; listRet = n.PesquisaSearchPF(filtro); if (listRet != null) { divResultado.Visible = true; if (listRet.Count > 0) { gridResult.DataSource = listRet; gridResult.DataBind(); Util.Format.OcultaColunaEspecificaGrid(ref gridResult, 4); Util.Format.OcultaColunaEspecificaGrid(ref gridResult, 5); Util.Format.OcultaColunaEspecificaGrid(ref gridResult, 6); Util.Format.OcultaColunaEspecificaGrid(ref gridResult, 7); } else { gridResult.DataSource = null; gridResult.EmptyDataText = "NENHUM REGISTRO ENCONTRADO."; gridResult.DataBind(); } //Transformando o Retorno em XML para gravar no banco var xns = new XmlSerializerNamespaces(); xns.Add(string.Empty, string.Empty); var xs = new XmlSerializer(listRet.GetType()); var xml = new StringWriter(); xs.Serialize(xml, listRet, xns); HTMLRetornado = xml.ToString(); string parametrosPesquisado = filtro.Nome + " | " + filtro.UF + " | " + filtro.Cidade; string NomeInternoProduto = "WEB RASTREAMENTO SEARCH PF"; Entidades.HistoricoPesquisa hist = SalvarHistoricoPesquisa("S", codigoItemProduto, "", parametrosPesquisado, "NOME | UF | CIDADE"); SalvarHistoricoFornecedor("S", hist.IdHistoricoConsulta, xml.ToString(), NomeInternoProduto, "DNA"); lblDataConsulta.Text = DataBR.ToString("dd/MM/yyyy") + " às " + DataBR.ToString("HH:mm"); lblNumeroConsulta.Text = hist.IdHistoricoConsulta.ToString().PadLeft(5, '0'); } else { lblMensagemRetorno.Visible = true; lblMensagemRetorno.Text = ""; lblMensagemRetorno.Text = "NENHUM REGISTRO ENCONTRADO.<br/><br/>"; string mensagemExibir = "<span id='lblTexto30DiasTexto1' class='texto' style='display:inline-block;font-weight:normal'>"; //mensagemExibir += ddlFiltro.Value.Trim().ToUpper() + ": <b>" + txtParametroInformado.Text + "</b>"; mensagemExibir += " </span><br/><br/>"; lblMensagemRetorno.Text += mensagemExibir; //divImprimirMensagemErro.Attributes.Add("style", "display:block;"); divEspacoBranco.Visible = true; divResultado.Visible = false; LimparCampos(); string parametrosPesquisado = filtro.Nome + " | " + filtro.UF + " | " + filtro.Cidade; string NomeInternoProduto = "WEB RASTREAMENTO SEARCH PF"; Entidades.HistoricoPesquisa hist = SalvarHistoricoPesquisa("N", codigoItemProduto, "", parametrosPesquisado, "NOME | UF | CIDADE"); SalvarHistoricoFornecedor("N", hist.IdHistoricoConsulta, "NENHUM REGISTRO ENCONTRADO.", NomeInternoProduto, "DNA"); lblDataConsulta.Text = DataBR.ToString("dd/MM/yyyy") + " às " + DataBR.ToString("HH:mm"); lblNumeroConsulta.Text = hist.IdHistoricoConsulta.ToString().PadLeft(5, '0'); //Page.ClientScript.RegisterStartupScript(this.GetType(), "Mensagem", "<script>alert('Veículo não encontrado.')</script>", false); } } catch (Exception ex) { Util.Log.Save("ex:" + ex.Message, "Consultar", "ConsultaWebRastreamentoSearchPF", HttpContext.Current.Server.MapPath(diretorioLog)); throw ex; } }
/// <summary> /// 保存する /// </summary> /// <param name="file">ファイルパス</param> public static void Save( string file) { if (table == null) { return; } var dir = Path.GetDirectoryName(file); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var work = new List <SpellTimer>( table.Where(x => !x.IsInstance)); foreach (var item in work) { item.MatchSound = !string.IsNullOrWhiteSpace(item.MatchSound) ? Path.GetFileName(item.MatchSound) : string.Empty; item.OverSound = !string.IsNullOrWhiteSpace(item.OverSound) ? Path.GetFileName(item.OverSound) : string.Empty; item.BeforeSound = !string.IsNullOrWhiteSpace(item.BeforeSound) ? Path.GetFileName(item.BeforeSound) : string.Empty; item.TimeupSound = !string.IsNullOrWhiteSpace(item.TimeupSound) ? Path.GetFileName(item.TimeupSound) : string.Empty; if (item.Font != null && item.Font.Family != null && !string.IsNullOrWhiteSpace(item.Font.Family.Source)) { item.FontFamily = string.Empty; item.FontSize = 1; item.FontStyle = 0; } } using (var sw = new StreamWriter(file, false, new UTF8Encoding(false))) { var xs = new XmlSerializer(work.GetType()); xs.Serialize(sw, work); } foreach (var item in work) { item.MatchSound = !string.IsNullOrWhiteSpace(item.MatchSound) ? Path.Combine(SoundController.Default.WaveDirectory, Path.GetFileName(item.MatchSound)) : string.Empty; item.OverSound = !string.IsNullOrWhiteSpace(item.OverSound) ? Path.Combine(SoundController.Default.WaveDirectory, Path.GetFileName(item.OverSound)) : string.Empty; item.BeforeSound = !string.IsNullOrWhiteSpace(item.BeforeSound) ? Path.Combine(SoundController.Default.WaveDirectory, Path.GetFileName(item.BeforeSound)) : string.Empty; item.TimeupSound = !string.IsNullOrWhiteSpace(item.TimeupSound) ? Path.Combine(SoundController.Default.WaveDirectory, Path.GetFileName(item.TimeupSound)) : string.Empty; } }
public ActionResult GetUserImages(int num, int p) { if (UserSession.CurrentUser == null) { return(Content("")); } IList <Inpinke_Image> list = DBImageBLL.GetUserImages(PageInfo, UserSession.CurrentUser.ID); if (list != null) { List <pagedata> photoList = new List <pagedata>(); foreach (Inpinke_Image i in list) { pagedata d = new pagedata() { id = i.ID, bigImg = "/userfile/" + UserSession.CurrentUser.ID + "/" + i.ImageName + "_edit.jpg", img = i.Path, title = string.IsNullOrEmpty(i.Remark) ? "" : i.Remark, }; string imgPath = Server.MapPath(d.img); d.img = "/userfile/" + UserSession.CurrentUser.ID + "/" + i.ImageName + "_view.jpg"; string vimgPath = Server.MapPath(d.img); if (!System.IO.File.Exists(imgPath)) { continue; } if (!System.IO.File.Exists(vimgPath)) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imgPath); if (originalImage != null) { Bitmap bitmap = new Bitmap(originalImage); ImageProcessBLL.CreateStaticScaleImage(bitmap, 220, 1, 1000, vimgPath); } else { continue; } } photoList.Add(d); } System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(photoList.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, photoList); return(Content(Encoding.UTF8.GetString(ms.ToArray()))); } } else { return(Content("")); } }
/// <summary> /// Creates list of users with given input array /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">List of user object</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse <Object> CreateUsersWithListInputWithHttpInfo(List <User> body) { // verify the required parameter 'body' is set if (body == null) { throw new ApiException(400, "Missing required parameter 'body' when calling UserApi->CreateUsersWithListInput"); } var localVarPath = "/user/createWithList"; var localVarPathParams = new Dictionary <String, String>(); var localVarQueryParams = new List <KeyValuePair <String, String> >(); var localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary <String, String>(); var localVarFileParams = new Dictionary <String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "*/*" }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) { localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); } if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = this.Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse)this.Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int)localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("CreateUsersWithListInput", localVarResponse); if (exception != null) { throw exception; } } return(new ApiResponse <Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null)); }
/// <summary> /// Converts an instance of an object to a string format /// </summary> /// <param name="format">Specifies if it should convert to XML, BSON or JSON</param> /// <returns>The object, converted to a string representation</returns> public string ToString(SerializationFormats format) { Encryption64 encryptor = new Encryption64(); List <DataLayer.FooEnterprises.Customer.SerializableCustomer> zs = new List <DataLayer.FooEnterprises.Customer.SerializableCustomer>(); foreach (Customer z in this) { DataLayer.FooEnterprises.Customer.SerializableCustomer serializableCustomer = new DataLayer.FooEnterprises.Customer.SerializableCustomer(); serializableCustomer.CustomerId = z.IsNull(Customer.Fields.CustomerId) ? (int?)null : z.CustomerId; serializableCustomer.FirstName = z.IsNull(Customer.Fields.FirstName) ? null : z.FirstName; serializableCustomer.LastName = z.IsNull(Customer.Fields.LastName) ? null : z.LastName; serializableCustomer.SerializationIsUpdate = z.LayerGenIsUpdate(); serializableCustomer.SerializationConnectionString = encryptor.Encrypt(z.LayerGenConnectionString(), DataLayer.FooEnterprises.Universal.LayerGenEncryptionKey); zs.Add(serializableCustomer); } if (format == SerializationFormats.Json) { return(Newtonsoft.Json.JsonConvert.SerializeObject(zs)); } if (format == SerializationFormats.Xml) { System.Xml.Serialization.XmlSerializer xType = new System.Xml.Serialization.XmlSerializer(zs.GetType()); using (System.IO.StringWriter sw = new System.IO.StringWriter()) { xType.Serialize(sw, zs); return(sw.ToString()); } } if (format == SerializationFormats.BsonBase64) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (Newtonsoft.Json.Bson.BsonWriter writer = new Newtonsoft.Json.Bson.BsonWriter(ms)) { Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Serialize(writer, zs); } return(Convert.ToBase64String(ms.ToArray())); } } return(""); }
/// <summary> /// Find the current UUID of multiple players at once Find the current players name, UUID, demo status and migration flag by the current players name. The \"at\" parameter is not supported. Players not found are not returned. If no players are found, an empty array is returned. /// </summary> /// <exception cref="Org.OpenAPITools.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="requestBody">Array with the player names</param> /// <returns>Task of ApiResponse (List<CurrentPlayerIDs>)</returns> public async System.Threading.Tasks.Task <ApiResponse <List <CurrentPlayerIDs> > > FindUniqueIdsByNameAsyncWithHttpInfo(List <string> requestBody) { // verify the required parameter 'requestBody' is set if (requestBody == null) { throw new ApiException(400, "Missing required parameter 'requestBody' when calling NameHistoryApi->FindUniqueIdsByName"); } var localVarPath = "/profiles/minecraft"; var localVarPathParams = new Dictionary <String, String>(); var localVarQueryParams = new List <KeyValuePair <String, String> >(); var localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader); var localVarFormParams = new Dictionary <String, String>(); var localVarFileParams = new Dictionary <String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) { localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); } if (requestBody != null && requestBody.GetType() != typeof(byte[])) { localVarPostBody = this.Configuration.ApiClient.Serialize(requestBody); // http body (model) parameter } else { localVarPostBody = requestBody; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int)localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("FindUniqueIdsByName", localVarResponse); if (exception != null) { throw exception; } } return(new ApiResponse <List <CurrentPlayerIDs> >(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List <CurrentPlayerIDs>) this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(List <CurrentPlayerIDs>)))); }
public static void GetUnlinkedReviews(List <Review> allReviews, List <CPU> cpuList, List <GPU> gpuList) { List <int> reviewIdList = new List <int>(); List <int> allReviewsIds = new List <int>(); //Add all review ids ti list foreach (var review in allReviews) { allReviewsIds.Add(review.Id); } #region add to shared list //add reviews with links to reviewIdList foreach (var cpu in cpuList) { reviewIdList = helper2(reviewIdList, cpu); } foreach (var gpu in gpuList) { reviewIdList = helper2(reviewIdList, gpu); } #endregion reviewIdList = allReviewsIds.Except(reviewIdList).ToList(); reviewIdList.Sort(); bool first = true; StringBuilder sb = new StringBuilder(); foreach (int id in reviewIdList) { if (first) { sb.Append("select title from Review where Review.productType = \"" + allReviews.GetType() + "\" AND ReviewID = "); sb.Append(id); first = false; } else { sb.Append(" or ReviewID = "); sb.Append(id); } } sb.Append(" group by title;"); Debug.WriteLine(sb); }
/// <summary> /// Writes the <see cref="_stubs"/> object including its metadata into the debug log in Json form /// </summary> protected void LogStubObjects() { _debugLogger.Debug("[#{0}]: {1}s: {2}{3}", _miNumber, _stubs.GetType().GetGenericArguments()[0].Name, Environment.NewLine, JsonConvert.SerializeObject(_stubs, Formatting.Indented, new JsonSerializerSettings { Converters = { new JsonByteArrayConverter(), new StringEnumConverter() } })); }
static void Main(string[] args) { sbyte asbyte = 4; short ashort = 4; int aint = 4; long along = 4; byte abyte = 4; ushort aushort = 4; uint auint = 4; ulong aulong = 4; char achar = 'm'; bool abool = true; float afloat = 4; double adouble = 4.44; decimal adecimal = 4; // Приведение Int16 int16 = 16; Int32 int32 = int16; Int64 int64 = int32; long lng = int64; double dbl = lng; float flt = (float)dbl; byte bt = (byte)flt; uint ui = (uint)bt; ulong ulng = (ulong)ui; ushort ushrt = (ushort)ulng; // Упаковка/распаковка Int16 i16 = 8; Object o = i16; byte b = (byte)(Int16)o; // Var var x = 'z'; var y = 32; var z = true; var mass = new List <int>(new int[] { 14, 15, 77, 55, 73, 245 }); Console.WriteLine(mass.GetType()); Console.WriteLine(); // Nullable int?x1 = null; int?x2 = null; Console.Write(x1 == x2); int?y1 = 2; // Null-объединение int?t = x1 ?? y1; int?g = y1 ?? x1; Console.WriteLine(t); Console.WriteLine(g); /// Задание №2 String strng1 = "Chechnya"; String strng2 = "Kruto"; char[] delim = { ' ' }; Console.WriteLine(String.Compare(strng1, strng2)); // Операции над строками String strng = "Это"; String tstrng = String.Join(" ", strng1, strng, strng2); Console.WriteLine(tstrng); strng2 = String.Copy(strng1); Console.WriteLine(strng2); String sstrng = tstrng.Substring(9, 3); Console.WriteLine(sstrng); String[] substrng = tstrng.Split(delim); Console.WriteLine(substrng[2]); String istrng = tstrng.Insert(13, "ОЧЕНЬ "); Console.WriteLine(istrng); String rstrng = istrng.Replace(substrng[0], null); Console.WriteLine(rstrng); String estrng = ""; String nstrng = null; Console.WriteLine("Is estrng empty? " + String.IsNullOrEmpty(estrng)); Console.WriteLine("Is nstrng empty? " + String.IsNullOrEmpty(nstrng)); //StringBuilder StringBuilder abc = new StringBuilder("ABC", 50); abc.Append(new char[] { 'D', 'E', 'F' }); abc.AppendFormat("GHI{0}{1}", "j", "K"); Console.WriteLine("{0} chars: {1}", abc.Length, abc.ToString()); abc.Insert(0, "Alphabet: "); abc.Replace('j', 'J'); Console.WriteLine("{0} chars: {1} ", abc.Length, abc.ToString()); abc.Remove(0, 10); Console.WriteLine("{0} chars: {1} ", abc.Length, abc.ToString()); abc.Insert(11, " is alphabet"); Console.WriteLine("{0} chars: {1} ", abc.Length, abc.ToString()); ///Массивы int pos; string change; //Матрица Console.WriteLine("Массив:"); int[,] arr = new int[4, 6]; Random rn = new Random(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 6; j++) { arr[i, j] = rn.Next(1, 10); Console.Write("{0}\t", arr[i, j]); } Console.WriteLine("{0}\n", ""); } //Стринговый string[] arr1 = { "Казнить", " ", "нельзя", " ", "помиловать" }; for (int n = 0; n < arr1.Length; n++) { Console.WriteLine("Номер элемента: " + n + ";\t" + arr1[n]); } Console.WriteLine("Длина массива строк: " + arr1.Length); Console.WriteLine("Введите номер элемента:"); pos = int.Parse(Console.ReadLine()); Console.WriteLine("Теперь введите строку:"); change = Console.ReadLine(); arr1[pos] = change; for (int i = 0; i < arr1.Length; i++) { Console.Write(arr1[i]); } Console.WriteLine(); //Ступенчатый int[][] myArr = new int[3][]; myArr[0] = new int[2]; myArr[1] = new int[3]; myArr[2] = new int[4]; Console.WriteLine("Введите значения массива:"); for (int i = 0; i < 2; i++) { myArr[0][i] = int.Parse(Console.ReadLine()); } for (int i = 0; i < 3; i++) { myArr[1][i] = int.Parse(Console.ReadLine()); } for (int i = 0; i < 4; i++) { myArr[2][i] = int.Parse(Console.ReadLine()); } Console.WriteLine(); for (int i = 0; i < 2; i++) { Console.Write("{0}\t", myArr[0][i]); } Console.WriteLine(); for (int i = 0; i < 3; i++) { Console.Write("{0}\t", myArr[1][i]); } Console.WriteLine(); for (int i = 0; i < 4; i++) { Console.Write("{0}\t", myArr[2][i]); } Console.WriteLine(); var v = new[] { 0, 1, 2, 3 }; var v1 = "kek"; ///Кортежи Console.WriteLine("\n\t\t\tРабота с кортежами"); var myTuple = Corteg(25, "Alexandr", 's', "hi", 245); Console.WriteLine("Кортеж полностью:"); Console.WriteLine("{0}\t", myTuple); Console.WriteLine("Кортеж частично:"); Console.WriteLine("{0}\t{1}\t{2}\t", myTuple.Item1, myTuple.Item3, myTuple.Item4); //Распаковка кортежа int it = (int)myTuple.Item1; Console.WriteLine(it); //Kортеж произвольной размерности var myTuple2 = Tuple.Create <int, char, string, decimal, float, byte, short, Tuple <int, string, char, string, ulong> >(12, 'C', "Name", 12.3892m, 0.5f, 120, 4501, myTuple); Console.WriteLine(myTuple.Equals(myTuple2)); }
/// <summary> /// Serializes the list clear. /// </summary> /// <param name="list">The list to serialize.</param> /// <returns></returns> protected override string SerializeListClear(List <T> list) { DateTime dtMetric = DateTime.UtcNow; string retval = JsonConvert.SerializeObject(list, Formatting.Indented); Device.Log.Metric(string.Format("SerializerJson.SerializeList: Type: {0} Size: {1} Time: {2:0} milliseconds", list.GetType(), (string.IsNullOrEmpty(retval) ? 0 : retval.Length), DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds)); return(retval); }
public static IQueryable <T> WhereContains <T, TProperty>(this IQueryable <T> query, Expression <Func <T, TProperty> > propertyExpression, IEnumerable <TProperty> array, Expression <Func <T, bool> > additionalExpression = null) { int count1 = 0; TProperty[] propertyArray = array as TProperty[] ?? array.ToArray <TProperty>(); int num = ((IEnumerable <TProperty>)propertyArray).Count <TProperty>(); ParameterExpression parameter = propertyExpression.Parameters[0]; List <Expression> source = new List <Expression>(); while (count1 < num) { int count2 = num - count1; if (num > 1000) { count2 = 1000; } List <TProperty> list = ((IEnumerable <TProperty>)propertyArray).Skip <TProperty>(count1).Take <TProperty>(count2).ToList <TProperty>(); source.Add((Expression)Expression.Call((Expression)Expression.Constant((object)list), list.GetType().GetTypeInfo().GetMethod("Contains"), new Expression[1] { propertyExpression.Body })); count1 += count2; } if (source.Count > 0) { Expression wholeExpression = source.First <Expression>(); foreach (var expr in source.Skip <Expression>(1)) { wholeExpression = Expression.MakeBinary(ExpressionType.OrElse, wholeExpression, expr); } Expression <Func <T, bool> > predicate = Expression.Lambda <Func <T, bool> >(wholeExpression, new ParameterExpression[1] { parameter }); if (additionalExpression != null) { predicate = Expression.Lambda <Func <T, bool> >((Expression)Expression.OrElse(additionalExpression.Body, wholeExpression), new ParameterExpression[1] { parameter }); } query = query.Where <T>(predicate); } else { var queryable = additionalExpression != null ? query.Where <T>(additionalExpression) : query.Where <T>((Expression <Func <T, bool> >)(x => false)); query = queryable; } return(query); }
static void Main(string[] args) { try { List <Edition> editions = new List <Edition>(); List <Book> books = new List <Book>(); List <Magazine> magazines = new List <Magazine>(); #region ReadFromFile string[] lines = File.ReadAllLines("../../file.txt"); for (int i = 0; i < lines.Length; i = i + 2) { EditionType editionType; try { if (!Enum.TryParse(lines[i], out editionType)) { throw new Exception("Wrong type of edition!"); } else if (editionType == EditionType.Book) { Book book = new Book(); book.ParseLine(lines[i + 1]); books.Add(book); editions.Add(book); } else if (editionType == EditionType.Magazine) { Magazine magazine = new Magazine(); magazine.ParseLine(lines[i + 1]); magazines.Add(magazine); editions.Add(magazine); } } catch (Exception ex) { OnError(ex.Message); } } #endregion OnAction("Data in file:"); outputList(editions); Console.WriteLine(); #region Menu string key; loop: OnAction("Menu"); Console.Write("Input key(sort, binary, xml): "); key = Console.ReadLine().ToLower(); switch (key) { case "sort": { #region Sort editions = editions.OrderBy(e => e.Name).ToList(); OnAction("Data in file(sorted by Name):"); outputList(editions); #endregion goto loop; } case "binary": { #region Binary BinaryFormatter formatter = new BinaryFormatter(); using (FileStream fs = new FileStream("editions.dat", FileMode.OpenOrCreate)) { formatter.Serialize(fs, editions); OnAction("Object was serialized BINARY!"); } List <Edition> deserializedEditions = new List <Edition>(); using (FileStream fs = new FileStream("editions.dat", FileMode.OpenOrCreate)) { deserializedEditions = (List <Edition>)formatter.Deserialize(fs); OnAction("Object was deserialized BINARY!"); outputList(deserializedEditions); } #endregion goto loop; } case "xml": { #region Xml XmlSerializer xmlSerializer = new XmlSerializer(editions.GetType(), new Type[] { typeof(Book), typeof(Magazine) }); using (FileStream fs = new FileStream("editions.xml", FileMode.OpenOrCreate)) { xmlSerializer.Serialize(fs, editions); OnAction("Object was serialized XML!"); } using (FileStream fs = new FileStream("editions.xml", FileMode.OpenOrCreate)) { List <Edition> deserializedEditions; deserializedEditions = (List <Edition>)xmlSerializer.Deserialize(fs); OnAction("Object was deserialized XML!"); outputList(deserializedEditions); } #endregion goto loop; } default: break; } #endregion } catch (Exception ex) { OnError(ex.Message); } Console.ReadLine(); }
private void browser_LoadCompleted(object sender, NavigationEventArgs e) { var document = browser.Document as mshtml.HTMLDocument; switch (currentStep) { case Steps.Starting: var usernameElem = document.getElementById("asdf"); usernameElem.setAttribute("value", Properties.Settings.Default.USERNAME); var passwordElem = document.getElementById("fdsa"); passwordElem.setAttribute("value", Properties.Settings.Default.PASSWORD); document.getElementsByName("submit").item(0).click(); currentStep = Steps.ExamAdministration; break; case Steps.ExamAdministration: browser.Navigate("https://www.fh-bielefeld.de/qisserver/rds?state=change&type=1&moduleParameter=studyPOSMenu&nextdir=change&next=menu.vm&subdir=applications&xml=menu&purge=y&navigationPosition=functions%2CstudyPOSMenu&breadcrumb=studyPOSMenu&topitem=functions&subitem=studyPOSMenu"); currentStep = Steps.GradeOverview; break; case Steps.GradeOverview: var links = document.getElementsByTagName("a"); foreach (HTMLAnchorElement link in links) { if (link.innerText != null && link.innerText.Contains("Notenspiegel")) { link.click(); } } currentStep = Steps.ChooseDegree; break; case Steps.ChooseDegree: var degrees = document.getElementsByTagName("a"); string searchPattern = "MA"; if (!Properties.Settings.Default.GET_MASTER) { searchPattern = "BA"; } foreach (HTMLAnchorElement degree in degrees) { if (degree.title != null && degree.title.Contains("Leistungen für Abschluss " + searchPattern)) { degree.click(); } } currentStep = Steps.ExamAdmin2; break; case Steps.ExamAdmin2: GetModulesMain(); // Main grades // exam administration browser.Navigate("https://www.fh-bielefeld.de/qisserver/rds?state=change&type=1&moduleParameter=studyPOSMenu&nextdir=change&next=menu.vm&subdir=applications&xml=menu&purge=y&navigationPosition=functions%2CstudyPOSMenu&breadcrumb=studyPOSMenu&topitem=functions&subitem=studyPOSMenu"); if (Properties.Settings.Default.GET_MASTER) { currentStep = Steps.ExternalGrades; } else { currentStep = Steps.Done; } break; case Steps.ExternalGrades: var links2 = document.getElementsByTagName("a"); foreach (HTMLAnchorElement link in links2) { if (link.innerText != null && link.innerText.Contains("Nur Noten für erbrachte Fremdleistungen")) { link.click(); } } currentStep = Steps.ExternalGradesClick; break; case Steps.ExternalGradesClick: var links3 = document.getElementsByTagName("a"); foreach (HTMLAnchorElement link in links3) { if (link.title != null && link.title.Contains("Leistungen für Abschluss BA")) { link.click(); } } currentStep = Steps.Done; break; case Steps.Done: GetModulesExternal(); // Main grades lViewModules.Items.Refresh(); XmlSerializer x = new System.Xml.Serialization.XmlSerializer(Modules.GetType()); using (var fs = new FileStream(filePath, FileMode.Create)) { x.Serialize(fs, Modules); } // Remove old foreach (Module module in Modules) { bool foundModule = false; foreach (Module oldModule in OldModules) { if (module.Name == oldModule.Name) { foundModule = true; } } if (!foundModule) { lViewModules.Items.Add(module); } } progressBar.IsIndeterminate = false; if (lViewModules.Items.Count > 0) { if (notifyIcon != null) { notifyIcon.ShowBalloonTip(10000, "New LSF entry!"); Dispatcher.Invoke(() => { Visibility = Visibility.Visible; this.ShowInTaskbar = true; }); } } break; } }
public void DeepCopy_DeepObject_Tests() { List <Dictionary <string, object> > list = new List <Dictionary <string, object> >(); Dictionary <string, object> dictionary1 = new Dictionary <string, object>(); dictionary1["abc"] = "def"; dictionary1["123"] = 456; dictionary1["Record"] = new { name = "Marcelo", city = "Seattle" }; dictionary1["Color"] = Color.White; dictionary1["Class"] = new TestClass { i = 9, s = "k" }; list.Add(dictionary1); Dictionary <string, object> dictionary2 = new Dictionary <string, object>(); dictionary2["ghi"] = Tuple.Create(1, "abc"); dictionary2["789"] = new Stack <string>(); ((Stack <string>)dictionary2["789"]).Push("Push it"); dictionary2["NewRecord"] = new { name = "Marcelo", city = "Seattle" }; dictionary2["Struct"] = new TestStruct { a = 27, s = "t" }; list.Add(dictionary2); var listCopy = (IList)(((object)list).DeepCopy()); Assert.AreEqual(list.GetType(), listCopy.GetType()); Assert.AreNotSame(list, listCopy); Assert.AreEqual(list.Count, listCopy.Count); for (int i = 0; i < list.Count; i++) { var dict = (IDictionary)list[i]; var dictCopy = (IDictionary)listCopy[i]; Assert.AreNotSame(dict, dictCopy); Assert.AreEqual(dict.GetType(), dictCopy.GetType()); foreach (DictionaryEntry item in dict) { bool found = false; foreach (var keyCopy in dictCopy.Keys) { if (item.Key.Equals(keyCopy)) { Assert.AreNotSame(keyCopy, item.Key); found = true; break; } } Assert.IsTrue(found); var valueCopy = dictCopy[item.Key]; Assert.AreEqual(item.Value, valueCopy); if (item.Value != null) { Assert.AreNotSame(item.Value, valueCopy); Assert.AreEqual(item.Value.GetType(), valueCopy.GetType()); } } } }
public void ThenItShouldBeFound() { Debug.Assert(result.GetType() == typeof(List <Contact>) && result != null); }
public void CreateHotelsList() { //holds value string hlID; string hlName; string hlRating; string hlRoomType; string hlDailyRate; string hlCapacity; //Reads hotels.xml data oldList = new List <Hotels>(); sr = new StreamReader(@"..\..\hotels.xml"); Serial = new XmlSerializer(oldList.GetType()); oldList = (List <Hotels>)Serial.Deserialize(sr); sr.Close(); //Reads roomtypes.xml data typeList = new List <RoomTypes>(); sr = new StreamReader(@"..\..\roomtypes.xml"); Serial = new XmlSerializer(typeList.GetType()); typeList = (List <RoomTypes>)Serial.Deserialize(sr); sr.Close(); //initialize newList newList = new List <HotelsList>(); //loop through oldList by each Hotel for (int i = 0; i < oldList.Count; i++) { hlID = oldList[i].id; //copy id to local var hlName = oldList[i].name; //copy name to local var hlRating = oldList[i].rating; //copy rating //create H and enter values from local vars HotelsList H = new HotelsList(hlID, hlName, hlRating); //loop through oldList RoomList by each room for (int j = 0; j < oldList[i].RoomList.Count; j++) { //loop through typeList by each RoomType for (int k = 0; k < typeList.Count; k++) { //check to see if each id == id for roomtype if (oldList[i].RoomList[j].id == typeList[k].id) { hlRoomType = typeList[k].name; //copy name to local var hlDailyRate = oldList[i].RoomList[j].rate; //copy rate to local var hlCapacity = oldList[i].RoomList[j].capacity; //copy capacity to local var //create R and enter values from local vars Room R = new Room(hlRoomType, hlDailyRate, hlCapacity); //add R to H Rooms H.AddRoomType(R); } } } //add H to newList newList.Add(H); } //Writes hotelslisting.xml Serial = new XmlSerializer(newList.GetType()); sw = new StreamWriter(HOTELSLISTING_FILENAME); Serial.Serialize(sw, newList); sw.Close(); }
/// <summary> /// LINQ /// </summary> /// <param name="args"></param> static void Main0(string[] args) { List <Car> myCars = new List <Car>() { new Car() { VIN = "A1", Make = "BMW", Model = "550i", StikerPrice = 55000, Year = 2009 }, new Car() { VIN = "B2", Make = "Toyota", Model = "4Runner", StikerPrice = 35000, Year = 2010 }, new Car() { VIN = "C3", Make = "BMW", Model = "74li", StikerPrice = 75000, Year = 2008 }, new Car() { VIN = "D4", Make = "Ford", Model = "Escape", StikerPrice = 25000, Year = 2008 }, new Car() { VIN = "E5", Make = "BMW", Model = "55i", StikerPrice = 57000, Year = 2010 }, }; // LINQ query var bmws = from car in myCars where car.Make == "BMW" && car.Year == 2010 select car; var orderedCars = from car in myCars orderby car.Year descending select car; // LINQ method var bmw2s = myCars.Where(c => c.Make == "BMW" && c.Year == 2010); var orderedCar2s = myCars.OrderByDescending(c => c.Year); var firstBMW = myCars.OrderByDescending(c => c.Year).First(); Console.WriteLine(firstBMW.VIN); Console.WriteLine(myCars.TrueForAll(c => c.Year > 2007)); myCars.ForEach(c => c.StikerPrice -= 3000);// 使用 ForEach 会对原链表进行修改 myCars.ForEach(c => Console.WriteLine("{0} {1:C}", c.VIN, c.StikerPrice)); Console.WriteLine(myCars.Exists(c => c.Model == "74li")); Console.WriteLine(myCars.Sum(c => c.StikerPrice)); foreach (var car in bmws) { Console.WriteLine($"{car.VIN} {car.Make} {car.Year}"); } Console.WriteLine(myCars.GetType()); var orderedCar3s = myCars.OrderByDescending(c => c.Year); Console.WriteLine(orderedCars.GetType()); var bmw3s = myCars.Where(c => c.Make == "BMW" && c.Year == 2010); Console.WriteLine(bmws.GetType()); var newCars = from car in myCars where car.Make == "BMW" // 匿名对象的初始化 select new { car.Make, car.Model }; // System.Linq.Enumerable+WhereSelectListIterator`2[LINQAndXML.Car,<>f__AnonymousType0`2[System.String,System.String]]:匿名对象 Console.WriteLine(newCars.GetType()); }