본문 바로가기
반응형

C#82

[Lambda] DataTable 조건 조회 Where,FirstOrDefault Wherestring ClsCode1 = cmbClass1.GetSelectedValue("Code").Substring(0, 2); string ClsCode2 = cmbClass1.GetSelectedValue("Code").Substring(2, 2); var dic = new Dictionary(); dic.Add("-", "== 선택 =="); var lst = _dtCode.Rows.Where(c => (c["ClsCode1"].ToStringOrEmpty() == ClsCode1 && c["ClsCode2"].ToStringOrEmpty() == ClsCode2)); foreach (Silverlight.DataRow dr in lst) dic.Add(dr["Basecode"].ToStrin.. 2015. 8. 26.
Collection(List)에 데이터 넣기 data table을 List로 넣기 var lst = new List; foreach(DataRow dr in rows) lst.Add(new string[]{dr["a], dr["b"], dr["c"]}); list 초기화 방법 List lst = new List(){"a", "b", "c"}; var lst = new List(){"a", "b", "c"}; string[] arr = { "a", "a", "b" }; List lst = new List(array); 2015. 8. 26.
Action 메서드 경우 1 base.InvokeService(strReturn => AcceptAction(strReturn), lst); protected void AcceptAction(string returnValue) { //To do. }-------------------------------------------------------------------------------------- 경우 2 Action onComplete = delegate(DataSet ds) { //To do. }; base.InvokeServiceDataSet(onComplete, dic);--------------------------------------------------------------------------------.. 2015. 8. 21.
CSV 파일 읽어오기 2가지 방법 string[] allLines = File.ReadAllLines(@"E:\Temp\data.csv"); var query = from line in allLines let data = line.Split(',') select new { Device = data[0] , SignalStrength = data[1] , Location = data[2] , Time = data[3] , Age = Convert.ToInt16(data[4]) }; -------------------------------------------------------------------------------------using System; using System.IO;class Program { static v.. 2015. 8. 21.
Dictionary 관련 유용코드 Dictionary foreach KeyValuePairforeach (KeyValuePair f in param) { parameters.AddWithValue("@" + f.Key, f.Value); } Dictionary 위치변경 list로 벼경후 현재 인댁스를 찾아서 가져다 붙이기 var codeIndex = map.Values.ToList().IndexOf(statusCode); var codeItem = map.Skip(codeIndex+1).Concat(map.Take(codeIndex)).First(); 2015. 8. 21.
c# Extention Code 확장 메서드 모음. /// /// 객체 복제 (프로퍼티 값만)/// /// 복제될 타입/// 원본 객체/// public static T CopyTo(this object Source) where T : class, new(){ Type t = Source.GetType(); PropertyInfo[] properties = t.GetProperties(); T returnvalue = new T(); foreach (PropertyInfo pi in properties) { if (pi.CanWrite) { pi.SetValue(returnvalue, pi.GetValue(Source, null), null); } } return returnvalue;} /// /// 객체 배열을 JSON 형식으로/// /// 객체 형식.. 2015. 8. 21.
Dataset Extension 데이터 존재 유무 체크, 값 등등 Dataset과 과련한 확장 메서드 /// /// DataRow 확장 객체 /// public static class DataRowExtention { /// /// 필드의 유무 확인 /// /// 대상 DataRow /// 대상 필드명 /// 필드 유무 public static bool Exists(this System.Data.DataRow TargetRow, string FieldName) { return TargetRow.Table.Columns.Contains(FieldName); } /// /// 해당 필드를 문자열 값으로 변환 /// /// 대상 DataRow /// 대상 필드명 /// Trim 비활성화 여부 /// 문자열 값 public static string ToString(this S.. 2015. 8. 21.
JSON array(or list) in C# var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}"; JavaScriptSerializer ser = new JavaScriptSerializer(); nameList myNames = ser.Deserialize(jsonData); 참고 사이트 JSON array(or list) in C# http://stackoverflow.com/questions/6935343/deserialize-json-arrayor-list-in-c-sharp 2015. 8. 21.
DataSet to List DataSet의 데이터를 List형태로 변환 하는 방법. public List GetAllProducts(string sqlQuery) { DataSet dsinsert = GetDataSet(sqlQuery, "tblProducts"); return (from row in dsinsert.Tables[0].AsEnumerable() select new ProductsDAL { Product_ID = row.Field("Product_ID"), ProductDescr = row.Field("ProductDescr"), }).ToList(); } 2015. 8. 21.
c# 참고할 만한 사이트 목록 Zip 압축: blog.naver.com/vackjangmi/120126808831 TryIconcrynut84.tistory.com/41 [C#]컴퓨터 종료/재시작/로그오프/취소 .NET(C#,ASP) seoddong.tistory.com/22[C#]작업관리자처럼 현재 실행중인 프로세스 목록 구하기 seoddong.tistory.com/24 2015. 8. 21.
Zip 압축 특정 폴더의 파일을 압축하는 프로그램 예제. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using ICSharpCode.SharpZipLib.Zip; namespace AutoZipTimer { public class ZipManager { /// /// 특정 폴더를 ZIP으로 압축 /// /// 압축 대상 폴더 경로 /// 저장할 ZIP 파일 경로 /// 압축 암호 /// 폴더 삭제 여부 /// 압축 성공 여부 public static bool ZipFiles(string targetFolderPath, string .. 2015. 8. 21.
소켓 관련 정보 블로그 전용뷰어 보기 소켓http://nowonbun.tistory.com/155 c#강좌 있음. 보기 http://k1rha.tistory.com/entry/C-%EA%B8%B0%EB%B3%B8-TCP-%EC%86%8C%EC%BC%93-%ED%86%B5%EC%8B%A0-%EC%98%88%EC%A0%9C-%EC%BD%94%EB%93%9C-Basic-socket-communication-in-C http://blog.daum.net/starkcb/46 http://imjuni.tistory.com/443 2015. 8. 21.
날짜 표현 형식 Datetime형 자료를 ToString을 사용하여 원하는 스타일로 날짜 형식을 변경할 수 있다. dateTime.ToString("yyyyMMdd"); dateTime.ToString("yyyy년 MM월 dd일"); dateTime.ToString("yyyy-MM-dd"); dateTime.ToString("yyyy/MM/dd");//안됨? dateTime.ToString("yyyy'/'MM'/'dd"); dateTime.ToString("yyyy'/'MM'/'dd HH:mm:ss.fff"); dateTime.ToString("yyyy.MM.dd"); dateTime.ToString("D"); dateTime.ToString("D"); dateTime.ToString("yyyy.MM.dd (ddd)").. 2015. 8. 19.
바이너리 파일 저장 텍스트가 아닌 바이너리 형태로 저장했다가 다시 불러온다. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace ConsoleApplication1 { [Serializable] public class PointData { public int groupID { get; set; } public float width { get; set; } public int transparency { get; set; } public string memo { get; set; } .. 2015. 8. 19.
winform 참고 사이트 http://blog.daum.net/poisonguy/3668545 투명선 http://translate.googleusercontent.com/translate_c?depth=1&hl=ko&langpair=en%7Cko&rurl=translate.google.co.kr&u=http://stackoverflow.com/questions/8433416/how-to-draw-a-transparent-line-on-winform&usg=ALkJrhiLXN_YvpBlv-2EZ4aR4OMOafBSvg http://www.scripter.co.kr/entry/WinForm-Graphic%EC%9D%84-PictureBox%EC%97%90-%EB%84%A3%EC%96%B4%EB%B3%B4%EC%9E%90 http:.. 2015. 8. 19.
Basic Synchronization(동기화) 전용뷰어 보기 참고 사이트 http://www.albahari.com/threading/part2.aspx#_Thread_Safety_and_NET_Framework_Types 2015. 8. 19.
파일 생성 개발 프로세스 파일 생성 단계 필요 class using System.IO; using System.Diagnostics; 1. FileStream 변수 선언 2. StreamWriter 변수 선언 3. DirectoryInfo 변수 선언 4. 해당 디렉터리가 없다면 만듬. 5. FileStream 변수 설정 6. StreamWriter 변수에 FileStream 변수 대응 7. StreamWriter 변수에 파일 작성 값 넣기 소스 DirectoryInfo di = null; FileStream file = null; StreamWriter sw = null; FileInfo fi = null; string dirPath = string.Empty; string fileName = string.Empty; List .. 2015. 8. 19.
is연산자와 as 연산자 is 연산자 : 두 객체가 동일한지 비교하는데 사용, is 연산자는 해당 객체가 is 오른쪽 형식과 호환되는지 확인만 한다. 객체 형식을 변경할 수 는 없다. char data = 'a'; if(data is char) System.Console.WriteLine("문자 데이터 입니다."); else System.Console.WriteLine("문자 데이터가 아닙니다."); as 연산자 : 객체가 호환되지 않으면 null 값을 할당, 호환되면 형식(casting)을 시켜준다. as 연산자는 강제 형변환과 비슷하며 변환시 예외가 발생하면 null을 채운다. [표현식] as [데이터타입] string obj = data as string; if(obj != null) { .... } 아래의 형태는 as 연.. 2015. 8. 19.
.net 코딩 가이드 라인 파일 참고. 2015. 8. 19.
쓰레드 Thread의 주요 메서드 Abort() 스레드를 종료 프로세스를 실행시켜 강제 종료합니다. Interrupt() WaitSleepJoin 스레드 상태 즉, 대기 중인 스레드를 중단합니다. Join() 스레드가 종료될 때까지 호출 스레드를 차단합니다. Sleep() 지정된 시간(밀리초)동안 스레드를 쉬게 합니다. Start() 현재 스레드의 상태를 Running으로 변경합니다.(스레드 시작) http://msdn.microsoft.com/ko-kr/library/ms173178(v=vs.80).aspx 스레드 예제 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threadin.. 2015. 8. 19.
숫자 형식 표현 표 숫자에 콤마(,) 찍기 int won = 123456890;Console.WriteLine(string.Format("{0:n0}", won)); Console.WriteLine(string.Format("{0}", won.ToString("n0"))); ; Console.WriteLine(string.Format("{0:#,##0}", won)); Console.WriteLine(string.Format("{0}", won.ToString("#,##0"))); //결과 //123,456,890 //123,456,890 //123,456,890 MS C# 라이브러리 참조전용뷰어 보기 String.Format 메서드를 사용하거나 String.Format을 호출하는 Console.Write 메서드를 통해 숫.. 2015. 8. 19.
레지스트리(등록,추가삭제) public class RegeditHelper { private const string strRegSubKey = @""Software\ECountSoftware""; public static void SetRegistry(string key, string value) { RegistryKey rk = null; try { rk = Registry.LocalMachine.OpenSubKey(strRegSubKey, true); if (rk == null) { //해당 이름으로 서브키를 생성한다. rk = Registry.LocalMachine.CreateSubKey(strRegSubKey); } //서브키 아래로 쓰기 rk.SetValue(key, value); } catch (Exception ex).. 2015. 8. 19.
반응형