C# 新狗{ Name=x.Name, BreedName=x.BreedName, }).ToList(); 返回结果;}
因此,诀窍是先然后C# 新狗{ Name=x.Name, BreedName=x.BreedName, }).ToList(); 返回结果;},c#,linq,linq-to-sql,C#,Linq,Linq To Sql,因此,诀窍是先然后ToList()。它立即进行查询并从数据库中获取数据。第二个技巧是选择项并使用对象初始值设定项生成加载项的新对象 希望这有帮助。您不能直接返回匿名类型,但可以通过泛型方法循环它们。大多数LINQ扩展方法也是如此。这里面没有什么神奇之处,尽管看起来它们会返回匿名类型。如果参数为匿名,则结果也可以是匿名的 var result = Repeat(new { Name = "Foo Bar", Age = 100 }, 10); private static IEnumerable
ToList()
。它立即进行查询并从数据库中获取数据。第二个技巧是选择项并使用对象初始值设定项生成加载项的新对象
希望这有帮助。您不能直接返回匿名类型,但可以通过泛型方法循环它们。大多数LINQ扩展方法也是如此。这里面没有什么神奇之处,尽管看起来它们会返回匿名类型。如果参数为匿名,则结果也可以是匿名的
var result = Repeat(new { Name = "Foo Bar", Age = 100 }, 10);
private static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
{
for(int i=0; i<count; i++)
{
yield return element;
}
}
var result=Repeat(新的{Name=“Foo-Bar”,年龄=100},10);
私有静态IEnumerable Repeat(TResult元素,int计数)
{
for(inti=0;i新的{Name,BreedName});
公共静态IQueryable GetDogsWithBreedNames(函数创建者)
{
var db=新的DogDataContext(ConnectString);
var结果=以db为单位的d
加入b。d上的品种等于b
选择创建者(d.Name,b.BreedName);
返回结果;
}
Dog
表中的BreedId
显然是Breed
表中相应行的外键。如果数据库设置正确,LINQ to SQL应自动在两个表之间创建关联。生成的Dog类将具有Breed属性,而Breed类应拥有一个Dogs集合。通过这种方式设置它,您仍然可以返回IEnumerable
,这是一个包含BREAD属性的对象。唯一需要注意的是,您需要在查询中预加载BREAD对象和dog对象,以便在处理完数据上下文后可以访问它们,并且(正如另一张海报所建议的那样)对集合执行一个方法,该方法将导致立即执行查询(在本例中为ToArray):
现在我意识到编译器不允许我返回一组匿名类型,因为它需要狗,但是有没有一种方法可以在不创建自定义类型的情况下返回它
使用object返回匿名类型列表,而不创建自定义类型。
这将在没有编译器错误的情况下工作(在.net 4.0中)。我将列表返回给客户端,然后在JavaScript上解析它:
public object GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
};
return result;
}
如果主要思想是使发送到数据库服务器的SQL select语句只包含必需的字段,而不是所有的实体字段,那么您可以执行以下操作:
public class Class1
{
public IList<Car> getCarsByProjectionOnSmallNumberOfProperties()
{
try
{
//Get the SQL Context:
CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext dbContext
= new CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext();
//Specify the Context of your main entity e.g. Car:
var oDBQuery = dbContext.Set<Car>();
//Project on some of its fields, so the created select statment that is
// sent to the database server, will have only the required fields By making a new anonymouse type
var queryProjectedOnSmallSetOfProperties
= from x in oDBQuery
select new
{
x.carNo,
x.eName,
x.aName
};
//Convert the anonymouse type back to the main entity e.g. Car
var queryConvertAnonymousToOriginal
= from x in queryProjectedOnSmallSetOfProperties
select new Car
{
carNo = x.carNo,
eName = x.eName,
aName = x.aName
};
//return the IList<Car> that is wanted
var lst = queryConvertAnonymousToOriginal.ToList();
return lst;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
throw;
}
}
}
公共类1
{
公共IList getCarsByProjectionOnSmallNumberOfProperties()
{
尝试
{
//获取SQL上下文:
CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext dbContext
=new CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext();
//指定主要实体的上下文,例如汽车:
var oDBQuery=dbContext.Set();
//项目的某些字段上,因此创建的选择语句
//发送到数据库服务器时,将通过创建新的匿名类型仅具有所需字段
var QueryProjectedOnSmallSetof属性
=从oDBQuery中的x开始
选择新的
{
x、 卡诺,
x、 艾娜,
x、 阿纳姆
};
//将匿名类型转换回主要实体,例如汽车
变量queryConvertAnonymousToOriginal
=来自queryProjectedOnSmallSetOfProperties中的x
选择新车
{
carNo=x.carNo,
eName=x.eName,
aName=x.aName
};
//返回所需的IList
var lst=queryConvertAnonymousToOriginal.ToList();
返回lst;
}
捕获(例外情况除外)
{
System.Diagnostics.Debug.WriteLine(例如ToString());
投掷;
}
}
}
在C#7中,您现在可以使用元组!…这样就不需要创建一个类来返回结果
下面是一个示例代码:
public List<(string Name, string BreedName)> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
}.ToList();
return result.Select(r => (r.Name, r.BreedName)).ToList();
}
public List GetDogsWithBreedNames()
{
var db=新的DogDataContext(ConnectString);
var结果=以db为单位的d
加入b。d上的品种等于b
选择新的
{
Name=d.Name,
BreedName=b.BreedName
}.ToList();
返回result.Select(r=>(r.Name,r.BreedName)).ToList();
}
您可能需要安装System.ValueTuple nuget软件包。尝试此操作以获取动态数据。您可以转换列表的代码
这并不能完全回答你的问题,但谷歌根据关键词引导我来到这里。这就是你可以从列表中查询匿名类型的方式:
var anon = model.MyType.Select(x => new { x.Item1, x.Item2});
嘿,我不是一个因为害怕被滥用而不想要特性的人,但是你能想象如果他们允许匿名类型被传递出去,我们会看到什么样的粗糙代码吗?(颤抖)我们可能会看到一些滥用。我们也可能会看到一些简单得多的代码,基本上我们只需要一个元组。不是所有的东西都需要是一个行为复杂的对象。有时“只是数据”是正确的事情。当然,在我看来。谢谢,所以您的偏好是创建类型,即使是这样的一次性视图?我有很多报告以不同的方式分割相同的数据,希望不必创建所有这些不同的类型(狗种、狗种等)我会尽量不需要用太多的方式对它进行切片,或者把切片部分放在需要数据的地方,这样你就可以使用匿名类型——但除此之外,是的。它在某些方面很糟糕,但我担心这就是生活:(我喜欢这种方法,但现在我不知道如何显示。)
void main() {
IEnumerable<Tuple<Dog,Breed>> dogs = GetDogsWithBreedNames();
foreach(Tuple<Dog,Breed> tdog in dogs)
{
Console.WriteLine("Dog {0} {1}", tdog.param1.Name, tdog.param2.BreedName);
}
}
internal Album GetAlbum(int albumId)
{
return Albums.SingleOrDefault(a => a.AlbumID == albumId);
}
var album = GetAlbum(1);
foreach (Photo photo in album.Photos)
{
[...]
}
public class DogWithBreed
{
public Dog Dog { get; set; }
public string BreedName { get; set; }
}
public IQueryable<DogWithBreed> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new DogWithBreed()
{
Dog = d,
BreedName = b.BreedName
};
return result;
}
public System.Collections.IEnumerable GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
};
return result.ToList();
}
...
using System.Web.Routing;
...
class Program
{
static void Main(string[] args)
{
object anonymous = CallMethodThatReturnsObjectOfAnonymousType();
//WHAT DO I DO WITH THIS?
//I know! I'll use a RouteValueDictionary from System.Web.dll
RouteValueDictionary rvd = new RouteValueDictionary(anonymous);
Console.WriteLine("Hello, my name is {0} and I am a {1}", rvd["Name"], rvd["Occupation"]);
}
private static object CallMethodThatReturnsObjectOfAnonymousType()
{
return new { Id = 1, Name = "Peter Perhac", Occupation = "Software Developer" };
}
}
public partial class Dog {
public string BreedName { get; set; }}
List<Dog> GetDogsWithBreedNames(){
var db = new DogDataContext(ConnectString);
var result = (from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
}).ToList()
.Select(x=>
new Dog{
Name = x.Name,
BreedName = x.BreedName,
}).ToList();
return result;}
var result = Repeat(new { Name = "Foo Bar", Age = 100 }, 10);
private static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
{
for(int i=0; i<count; i++)
{
yield return element;
}
}
var result = GetDogsWithBreedNames((Name, BreedName) => new {Name, BreedName });
public static IQueryable<TResult> GetDogsWithBreedNames<TResult>(Func<object, object, TResult> creator)
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select creator(d.Name, b.BreedName);
return result;
}
public IEnumerable<Dog> GetDogs()
{
using (var db = new DogDataContext(ConnectString))
{
db.LoadOptions.LoadWith<Dog>(i => i.Breed);
return db.Dogs.ToArray();
}
}
foreach (var dog in GetDogs())
{
Console.WriteLine("Dog's Name: {0}", dog.Name);
Console.WriteLine("Dog's Breed: {0}", dog.Breed.Name);
}
public object GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
};
return result;
}
public class Class1
{
public IList<Car> getCarsByProjectionOnSmallNumberOfProperties()
{
try
{
//Get the SQL Context:
CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext dbContext
= new CompanyPossessionsDAL.POCOContext.CompanyPossessionsContext();
//Specify the Context of your main entity e.g. Car:
var oDBQuery = dbContext.Set<Car>();
//Project on some of its fields, so the created select statment that is
// sent to the database server, will have only the required fields By making a new anonymouse type
var queryProjectedOnSmallSetOfProperties
= from x in oDBQuery
select new
{
x.carNo,
x.eName,
x.aName
};
//Convert the anonymouse type back to the main entity e.g. Car
var queryConvertAnonymousToOriginal
= from x in queryProjectedOnSmallSetOfProperties
select new Car
{
carNo = x.carNo,
eName = x.eName,
aName = x.aName
};
//return the IList<Car> that is wanted
var lst = queryConvertAnonymousToOriginal.ToList();
return lst;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
throw;
}
}
}
public List<(string Name, string BreedName)> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
}.ToList();
return result.Select(r => (r.Name, r.BreedName)).ToList();
}
public object GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
};
return result.FirstOrDefault();
}
dynamic dogInfo=GetDogsWithBreedNames();
var name = dogInfo.GetType().GetProperty("Name").GetValue(dogInfo, null);
var breedName = dogInfo.GetType().GetProperty("BreedName").GetValue(dogInfo, null);
var anon = model.MyType.Select(x => new { x.Item1, x.Item2});