질문이 많습니다. 첫 번째 질문은 파일의 단어와 일치하는 간단한 LINQ 쿼리를 어떻게 만듭니 까? 나는 어리 석 으려고하지는 않지만 LINQ에서 찾은 문서를 제대로 이해하지 못했습니다.LINQ를 사용하여 단어를 일치 시키려면 어떻게합니까?
답변
보증 생각하십니까.
you''ll는 라벨 레이블 컨트롤, 텍스트 상자 및 버튼을 추가 할 필요가
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
namespace LinqTests
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public String[]
Content;
public String
Value;
private void button1_Click(object sender, EventArgs e)
{
Value = textBox1.Text;
OpenFileDialog ofile = new OpenFileDialog();
ofile.Title = "Open File";
ofile.Filter = "All Files (*.*)|*.*";
if (ofile.ShowDialog() == DialogResult.OK)
{
Content =
File.ReadAllLines(ofile.FileName);
IEnumerable<String> Query =
from instance in Content
where instance.Trim() == Value.Trim()
orderby instance
select instance;
foreach (String Item in Query)
label1.Text +=
Item + Environment.NewLine;
}
else Application.DoEvents();
ofile.Dispose();
}
}
}
나는이 여기
음 그래. 그것은 실제로 나를 도와줍니다. 감사합니다 – user164203
좋은 예. 'Value' ('textBox1.Text')와 같은 줄을 찾는다는 것을주의하십시오. 'instance.Trim()'이있는 행을'instance.Trim(). Contains (Value)'또는 이와 유사한 것으로 변경하십시오. – Abel
Abel에게 감사드립니다. 매우 감사. –
다음과 같은 경우는 어떻게됩니까?
테 코드는 파일을 읽고 단어로 분할 한 다음은 그 someword
를 불렀다 발견 한 첫 번째 단어를 반환하여 작동합니다 (지금까지 C#을 간결 될 수 없음? 말했다)
string yourFileContents = File.ReadAllText("c:/file.txt");
string foundWordOrNull = Regex.Split(yourFileContents, @"\w").FirstOrDefault(s => s == "someword");
.
편집 : 위에서 언급 한 내용은 "not LINQ"로 간주됩니다. 나는 (주석 참조) 동의하지 않습니다 만, 나는 같은 접근 방식보다 LINQified 예제에서는 새 WindowsForms 응용 프로그램을 만들고 다음 코드를 사용하여 여기에 ;-)
string yourFileContents = File.ReadAllText("c:/file.txt");
var foundWords = from word in Regex.Split(yourFileContents, @"\w")
where word == "someword"
select word;
if(foundWords.Count() > 0)
// do something with the words found
나는 downvoting하는 것을 꺼리지 만, 왜 코드가 잘못된지 설명하는 것은 매우 예의 바른 행동이다. – Abel
사용자가 특별히 Linq 샘플을 요청했기 때문에 나는 다운 투표했습니다. 정규 표현식이 아닙니다. –
설명해 주셔서 감사합니다. 나는 Linq의'FirstOrDefault' 부분을 고려합니다. 묻는 사람은 도우미를 사용하는 것이 금지되었다고 명시하지 않았습니다. 다른 예제는'String.Split'을 사용합니다. Linq로 분할하는 것은 불가능합니다 (그렇습니다. 그러나 char 배열에서는 지루할 것입니다). – Abel
을하는 데 도움이에서 단어의 발생 수를 계산 MSDN에서 예를 바랍니다 문자열 (http://msdn.microsoft.com/en-us/library/bb546166.aspx). 여기
string text = ...;
string searchTerm = "data";
//Convert the string into an array of words
string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' },
StringSplitOptions.RemoveEmptyEntries);
// Create and execute the query. It executes immediately
// because a singleton value is produced.
// Use ToLowerInvariant to match "data" and "Data"
var matchQuery = from word in source
where word.ToLowerInvariant() == searchTerm.ToLowerInvariant()
select word;
// Count the matches.
int wordCount = matchQuery.Count();
Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.",
wordCount, searchTerm);
그리고 텍스트 파일 http://www.onedotnetway.com/tutorial-reading-a-text-file-using-linq/에서 데이터를 읽는 하나 더 LINQ 튜토리얼입니다.
시도 했습니까? – ChrisF