첫 번째 열을 건너 뛰고 다른 열에서 구별됩니다
-
06-07-2019 - |
문제
아래의 TextFile 디스플레이에서 별개의 행을 선택해야합니다.
텍스트 파일
123| one| two| three <br/>
124| one| two| four <br/>
125| one |two| three <br/>
출력은 이것을 좋아해야합니다
123| one| two| three <br/>
124| one| two| four <br/>
또는
124| one| two| four <br/>
125| one |two| three <br/>
이 코드를 사용 하여이 문제를 해결하고 있습니다.
var readfile = File.ReadAllLines(" text file location ");
var spiltfile = (from f in readfile
let line = f.Split('|')
let y = line.Skip(1)
select (from str in y
select str).FirstOrDefault()).Distinct()
감사
해결책
문제의 불분명 한 간격은 도움이되지 않습니다 (특히 그 주변에 |two|
, 나머지와 다른 간격을 가지고 있는데, 이는 트리밍을 사용해야한다는 것을 암시하지만, 여기에는 작업을 수행하는 몇 가지 사용자 정의 LINQ 메소드가 있습니다. 나는 anon 유형을 순전히 일관되지 않은 간격을 평평하게하는 간단한 방법으로 사용했습니다 (나는 또한 끈을 재건 할 수 있었지만 불필요하게 보였습니다).
이상한 간격이 없으면 간단 할 수 있습니다.
var qry = ReadLines("foo.txt")
.DistinctBy(line => line.Substring(line.IndexOf('|')));
전체 코드 :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
static class Program
{
static void Main()
{
var qry = (from line in ReadLines("foo.txt")
let parts = line.Split('|')
select new
{
Line = line,
Key = new
{
A = parts[1].Trim(),
B = parts[2].Trim(),
C = parts[3].Trim()
}
}).DistinctBy(row => row.Key)
.Select(row => row.Line);
foreach (var line in qry)
{
Console.WriteLine(line);
}
}
static IEnumerable<TSource> DistinctBy<TSource, TValue>(
this IEnumerable<TSource> source,
Func<TSource, TValue> selector)
{
var found = new HashSet<TValue>();
foreach (var item in source)
{
if (found.Add(selector(item))) yield return item;
}
}
static IEnumerable<string> ReadLines(string path)
{
using (var reader = File.OpenText(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
}
다른 팁
이것을 확인하십시오, 이것은 당신이하고 싶은 일을 할 것입니다
static void Main(string[] args)
{
string[] readfile = System.IO.File.ReadAllLines(@"D:\1.txt");
var strList = readfile.Select(x => x.Split('|')).ToList();
IEnumerable<string[]> noduplicates =strList.Distinct(new StringComparer());
foreach (var res in noduplicates)
Console.WriteLine(res[0] + "|" + res[1] + "|" + res[2] + "|" + res[3]);
}
그리고 구현 iqualitycomparer 이 방법
class StringComparer : IEqualityComparer<string[]>
{
public bool Equals(string[] x, string[] y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x[1].Trim() == y[1].Trim() && x[2].Trim() == y[2].Trim() && x[3].Trim() == y[3].Trim() ;
}
public int GetHashCode(string[] data)
{
if (Object.ReferenceEquals(data, null)) return 0;
int hash1 = data[1] == null ? 0 : data[1].Trim().GetHashCode();
int hash2 = data[2] == null ? 0 : data[2].Trim().GetHashCode();
int hash3 = data[3] == null ? 0 : data[3].Trim().GetHashCode();
return hash1 ^ hash2 * hash3;
}
}
예상대로 출력을 줄 것입니다.
제휴하지 않습니다 StackOverflow